// ═══════════════════════════════════════════════
// JAGTAR STUDIO — Customer Account (login + orders)
// Three views: identifier → OTP entry → profile.
// Uses email or phone OTP via /api/customer/auth/*.
// ═══════════════════════════════════════════════

const JagtarAccount = ({ onNavigate }) => {
  const { c, H2, H3, Body, Label, CTA, Section, Field } = JAGTAR;

  const [stage, setStage] = React.useState('checking'); // checking | login | otp | profile
  const [mode, setMode] = React.useState('email'); // email | phone
  const [identifier, setIdentifier] = React.useState('');
  const [maskedIdentifier, setMaskedIdentifier] = React.useState('');
  const [code, setCode] = React.useState('');
  const [devCode, setDevCode] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [info, setInfo] = React.useState(null);
  const [customer, setCustomer] = React.useState(null);
  const [orders, setOrders] = React.useState([]);
  const [expandedOrder, setExpandedOrder] = React.useState(null);

  // On mount: see if we already have a customer session.
  React.useEffect(() => {
    (async () => {
      try {
        const res = await window.api('/api/customer/auth/me');
        if (res.ok) {
          const data = await res.json();
          setCustomer(data.customer);
          await loadOrders();
          setStage('profile');
        } else {
          setStage('login');
        }
      } catch {
        setStage('login');
      }
    })();
  }, []);

  async function loadOrders() {
    try {
      const res = await window.api('/api/customer/orders');
      if (res.ok) {
        const data = await res.json();
        setOrders(data.orders || []);
        setCustomer(c => c || data.customer);
        if ((data.orders || []).length > 0 && !expandedOrder) {
          setExpandedOrder(data.orders[0].order_number);
        }
      }
    } catch { /* ignore */ }
  }

  async function requestOtp() {
    setBusy(true); setError(null); setInfo(null); setDevCode(null);
    try {
      const res = await window.api('/api/customer/auth/request-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ identifier: identifier.trim() }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error((data && data.error) || `Request failed (${res.status})`);
      setMaskedIdentifier(data.identifier_masked || identifier);
      if (data.dev_code) setDevCode(data.dev_code);
      setStage('otp');
      setInfo(`Code sent to ${data.identifier_masked || identifier}`);
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }

  async function verifyOtp() {
    setBusy(true); setError(null);
    try {
      const res = await window.api('/api/customer/auth/verify-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ identifier: identifier.trim(), code: code.trim() }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error((data && data.error) || `Verification failed (${res.status})`);
      setCustomer(data.customer);
      await loadOrders();
      setStage('profile');
      setCode('');
      setInfo(null);
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }

  async function logout() {
    await window.api('/api/customer/auth/logout', { method: 'POST' });
    setCustomer(null);
    setOrders([]);
    setIdentifier('');
    setCode('');
    setStage('login');
  }

  // ─── Stage: checking ───
  if (stage === 'checking') {
    return (
      <div style={{ paddingTop: 72 }}>
        <Section>
          <div style={{ maxWidth: 420, margin: '0 auto', textAlign: 'center', color: c.gray }}>
            <Body small>Loading your account…</Body>
          </div>
        </Section>
      </div>
    );
  }

  // ─── Stage: login ───
  if (stage === 'login') {
    const inputLabel = mode === 'email' ? 'Email address' : 'Phone number';
    const placeholder = mode === 'email' ? 'jane@example.com' : '+44 7700 900123';
    const valid = mode === 'email'
      ? /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(identifier.trim())
      : /^\+?[1-9][\d\s\-().]{6,20}$/.test(identifier.trim());

    return (
      <div style={{ paddingTop: 72 }}>
        <Section>
          <div style={{ maxWidth: 440, margin: '0 auto' }}>
            <div style={{ textAlign: 'center', marginBottom: 32 }}>
              <Label style={{ display: 'block', marginBottom: 12 }}>Your Account</Label>
              <H2 style={{ fontSize: 'clamp(28px, 4vw, 40px)' }}>Sign in</H2>
              <Body small style={{ color: c.gray, marginTop: 12, maxWidth: 360, margin: '12px auto 0' }}>
                Enter your email or phone — we’ll send you a six-digit code. No password needed.
              </Body>
            </div>

            {/* Mode toggle */}
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr',
              border: `1px solid ${c.border}`, marginBottom: 28,
            }}>
              {[['email', 'Email'], ['phone', 'Phone']].map(([key, label]) => (
                <button
                  key={key}
                  onClick={() => { setMode(key); setIdentifier(''); setError(null); }}
                  style={{
                    fontFamily: "'Manrope', sans-serif", fontSize: 12,
                    letterSpacing: '0.1em', textTransform: 'uppercase',
                    padding: '12px 20px',
                    border: 'none', cursor: 'pointer',
                    background: mode === key ? c.charcoal : 'transparent',
                    color: mode === key ? c.bg : c.gray,
                    transition: 'all 0.2s ease',
                  }}
                >{label}</button>
              ))}
            </div>

            {error && (
              <div style={{
                padding: '10px 14px', marginBottom: 16, fontSize: 13,
                background: '#faecec', borderLeft: `3px solid ${c.error}`,
                color: '#6a2222',
              }}>{error}</div>
            )}

            <Field
              label={inputLabel}
              placeholder={placeholder}
              type={mode === 'email' ? 'email' : 'tel'}
              value={identifier}
              onChange={e => setIdentifier(e.target.value)}
              autoComplete={mode === 'email' ? 'email' : 'tel'}
              required
            />

            <CTA
              onClick={() => valid && !busy && requestOtp()}
              style={{
                width: '100%', marginTop: 8,
                ...(!valid || busy ? { opacity: 0.5, cursor: 'not-allowed' } : {}),
              }}
            >
              {busy ? 'Sending code…' : 'Send code'}
            </CTA>

            <Body small style={{ color: c.gray, marginTop: 24, textAlign: 'center' }}>
              We use the email or phone you placed your order with. Don’t have an order yet?{' '}
              <a onClick={(e) => { e.preventDefault(); onNavigate('product'); }}
                href="#"
                style={{ color: c.charcoal, textDecoration: 'underline' }}>
                Start a commission
              </a>.
            </Body>
          </div>
        </Section>
      </div>
    );
  }

  // ─── Stage: OTP entry ───
  if (stage === 'otp') {
    return (
      <div style={{ paddingTop: 72 }}>
        <Section>
          <div style={{ maxWidth: 440, margin: '0 auto' }}>
            <div style={{ textAlign: 'center', marginBottom: 32 }}>
              <Label style={{ display: 'block', marginBottom: 12 }}>Verify</Label>
              <H2 style={{ fontSize: 'clamp(28px, 4vw, 40px)' }}>Enter your code</H2>
              <Body small style={{ color: c.gray, marginTop: 12 }}>
                We sent a 6-digit code to <strong style={{ color: c.charcoal }}>{maskedIdentifier}</strong>.
                It expires in 10 minutes.
              </Body>
              {devCode && (
                <div style={{
                  marginTop: 16, padding: '10px 14px',
                  background: c.cream, borderLeft: `3px solid ${c.gold}`,
                  fontSize: 13, color: c.charcoal, textAlign: 'left',
                }}>
                  <strong>Dev mode:</strong> code is <code style={{ fontSize: 15, letterSpacing: 2 }}>{devCode}</code>
                  <div style={{ fontSize: 11, color: c.gray, marginTop: 4 }}>
                    (Returned in the API response when NODE_ENV ≠ production. Will be removed in production with real Resend / Twilio delivery.)
                  </div>
                </div>
              )}
            </div>

            {error && (
              <div style={{
                padding: '10px 14px', marginBottom: 16, fontSize: 13,
                background: '#faecec', borderLeft: `3px solid ${c.error}`,
                color: '#6a2222',
              }}>{error}</div>
            )}

            <input
              value={code}
              onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
              placeholder="000000"
              autoComplete="one-time-code"
              inputMode="numeric"
              maxLength={6}
              style={{
                width: '100%', boxSizing: 'border-box',
                padding: '20px 16px',
                fontFamily: "'Cormorant Garamond', Georgia, serif",
                fontSize: 32, textAlign: 'center', letterSpacing: '0.4em',
                color: c.charcoal,
                border: `1px solid ${c.border}`,
                background: '#fff',
                outline: 'none', marginBottom: 20,
              }}
              onFocus={e => e.target.style.borderColor = c.gold}
              onBlur={e => e.target.style.borderColor = c.border}
            />

            <CTA
              onClick={() => code.length >= 4 && !busy && verifyOtp()}
              style={{
                width: '100%',
                ...(code.length < 4 || busy ? { opacity: 0.5, cursor: 'not-allowed' } : {}),
              }}
            >
              {busy ? 'Verifying…' : 'Verify and sign in'}
            </CTA>

            <div style={{ marginTop: 20, textAlign: 'center' }}>
              <button
                onClick={() => { setStage('login'); setError(null); setCode(''); setDevCode(null); }}
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  fontFamily: "'Manrope', sans-serif", fontSize: 13,
                  color: c.gray, padding: 0,
                }}
              >← Use a different {mode === 'email' ? 'email' : 'number'}</button>
            </div>
          </div>
        </Section>
      </div>
    );
  }

  // ─── Stage: profile ───
  return <ProfileView
    customer={customer}
    orders={orders}
    expandedOrder={expandedOrder}
    setExpandedOrder={setExpandedOrder}
    onLogout={logout}
    onNavigate={onNavigate}
  />;
};

// ─── Profile / orders view ───
const ProfileView = ({ customer, orders, expandedOrder, setExpandedOrder, onLogout, onNavigate }) => {
  const { c, H2, H3, Body, Label, CTA, Section } = JAGTAR;

  const fmtDate = (ts) => ts ? new Date(ts).toLocaleDateString(undefined, {
    month: 'long', day: 'numeric', year: 'numeric',
  }) : '—';
  const fmtMonthYear = (ts) => ts ? new Date(ts).toLocaleDateString(undefined, {
    month: 'long', year: 'numeric',
  }) : '—';
  const fmtShort = (ts) => ts ? new Date(ts).toLocaleDateString(undefined, {
    month: 'short', day: 'numeric',
  }) : '';

  const StatusBadge = ({ status, label }) => {
    const colors = {
      order_placed:    { bg: 'rgba(184,181,176,0.15)', color: c.gray },
      photos_reviewed: { bg: 'rgba(184,181,176,0.15)', color: c.gray },
      sculpting:       { bg: 'rgba(176,141,92,0.12)',  color: c.gold },
      finishing:       { bg: 'rgba(201,123,92,0.12)',  color: c.terracotta },
      shipped:         { bg: 'rgba(92,122,92,0.12)',   color: c.success },
    };
    const s = colors[status] || colors.order_placed;
    return (
      <span style={{
        display: 'inline-block', padding: '4px 12px', borderRadius: 20,
        background: s.bg, color: s.color,
        fontFamily: "'Manrope', sans-serif", fontSize: 11,
        fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase',
      }}>{label}</span>
    );
  };

  const customerLabel = customer?.email || customer?.phone || 'Guest';
  const customerName = customer?.name || customer?.email?.split('@')[0] || 'Welcome';

  return (
    <div style={{ paddingTop: 72 }}>
      <Section>
        <div style={{ maxWidth: 760, margin: '0 auto' }}>
          {/* Customer header */}
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
            marginBottom: 48, flexWrap: 'wrap', gap: 16,
          }}>
            <div>
              <Label style={{ display: 'block', marginBottom: 8 }}>Your Account</Label>
              <H2 style={{ fontSize: 'clamp(26px, 3vw, 36px)' }}>{customerName}</H2>
              <Body small style={{ color: c.gray, marginTop: 4 }}>
                {customerLabel}{customer?.created_at ? ` · Member since ${fmtMonthYear(customer.created_at)}` : ''}
              </Body>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <button onClick={onLogout} style={{
                fontFamily: "'Manrope', sans-serif", fontSize: 12,
                letterSpacing: '0.1em', textTransform: 'uppercase',
                background: 'none', border: 'none', cursor: 'pointer',
                color: c.gray, padding: '12px 0',
                borderBottom: `1px solid ${c.border}`,
              }}>Sign out</button>
              <CTA onClick={() => onNavigate('product')} style={{ padding: '12px 24px', fontSize: 12 }}>
                New Commission
              </CTA>
            </div>
          </div>

          {/* Empty state */}
          {orders.length === 0 && (
            <div style={{
              padding: 'clamp(40px, 6vw, 80px) 24px',
              textAlign: 'center', border: `1px solid ${c.border}`, background: '#fff',
            }}>
              <H3 style={{ marginBottom: 8 }}>No orders yet</H3>
              <Body small style={{ color: c.gray, marginBottom: 24, maxWidth: 360, margin: '0 auto 24px' }}>
                When you place your first commission, it’ll show up here with a step-by-step timeline.
              </Body>
              <CTA onClick={() => onNavigate('product')}>Start a commission</CTA>
            </div>
          )}

          {/* Orders */}
          {orders.length > 0 && <Label style={{ display: 'block', marginBottom: 20 }}>Your Orders</Label>}

          {orders.map(order => {
            const expanded = expandedOrder === order.order_number;
            return (
              <div key={order.order_number} style={{
                border: `1px solid ${expanded ? c.gold : c.border}`,
                marginBottom: 16,
                background: '#fff',
                transition: 'border-color 0.3s ease',
              }}>
                {/* Order header */}
                <div
                  onClick={() => setExpandedOrder(expanded ? null : order.order_number)}
                  style={{
                    padding: 'clamp(16px, 2vw, 24px)',
                    cursor: 'pointer',
                    display: 'grid',
                    gridTemplateColumns: '1fr auto',
                    gap: 16, alignItems: 'center',
                  }}
                >
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                      <Body small style={{ fontWeight: 600, color: c.charcoal }}>#{order.order_number}</Body>
                      <StatusBadge status={order.status} label={order.status_label} />
                    </div>
                    <Body small style={{ color: c.gray, marginTop: 4 }}>
                      {order.item} · {fmtDate(order.placed_at)} · {order.currency} ${Number(order.total_amount).toFixed(2)}
                    </Body>
                  </div>
                  <span style={{
                    fontSize: 18, color: c.gray,
                    transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
                    transition: 'transform 0.3s ease',
                    display: 'inline-block',
                  }}>▾</span>
                </div>

                {/* Expanded detail */}
                {expanded && (
                  <div style={{
                    padding: '0 clamp(16px, 2vw, 24px) clamp(16px, 2vw, 24px)',
                    borderTop: `1px solid ${c.border}`,
                  }}>
                    {/* Progress timeline */}
                    <div style={{ padding: '24px 0' }}>
                      <div style={{ display: 'flex', gap: 0, alignItems: 'flex-start' }}>
                        {order.steps.map((step, i) => (
                          <div key={i} style={{ flex: 1, position: 'relative' }}>
                            {i < order.steps.length - 1 && (
                              <div style={{
                                position: 'absolute', top: 8, left: 'calc(50% + 8px)', right: '-50%',
                                height: 2,
                                background: step.done ? c.gold : c.border,
                              }} />
                            )}
                            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>
                              <div style={{
                                width: 16, height: 16, borderRadius: '50%',
                                background: step.done ? c.gold : step.active ? '#fff' : c.border,
                                border: step.active ? `2px solid ${c.gold}` : 'none',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                              }}>
                                {step.done && (
                                  <svg width="8" height="8" viewBox="0 0 12 12" fill="none" stroke="#fff" strokeWidth="2">
                                    <polyline points="2 6 5 9 10 3" strokeLinecap="round" strokeLinejoin="round" />
                                  </svg>
                                )}
                              </div>
                              <Body small style={{
                                fontSize: 11, textAlign: 'center', marginTop: 6,
                                color: step.done || step.active ? c.charcoal : c.gray,
                                fontWeight: step.active ? 600 : 400,
                              }}>{step.label}</Body>
                              <Body small style={{ fontSize: 10, color: c.gray, marginTop: 2, textAlign: 'center' }}>
                                {step.active ? 'In progress' : fmtShort(step.date)}
                              </Body>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Order details */}
                    <div style={{ paddingTop: 16, borderTop: `1px solid ${c.border}` }}>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '8px 24px' }}>
                        {[
                          ['Order', `#${order.order_number}`],
                          ['Date', fmtDate(order.placed_at)],
                          ['Photos submitted', `${order.photos_submitted} photos`],
                          [order.delivered_at ? 'Delivered' : 'Est. delivery', fmtDate(order.delivered_at || order.estimated_delivery_at)],
                        ].map(([k, v]) => (
                          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0' }}>
                            <Body small style={{ color: c.gray, fontSize: 13 }}>{k}</Body>
                            <Body small style={{ fontWeight: 500, color: c.charcoal, fontSize: 13 }}>{v}</Body>
                          </div>
                        ))}
                      </div>
                    </div>

                    {order.delivered_at && (
                      <div style={{
                        marginTop: 16, padding: 16,
                        background: 'rgba(92,122,92,0.06)', textAlign: 'center',
                      }}>
                        <Body small style={{ color: c.success }}>
                          Delivered on {fmtDate(order.delivered_at)}
                        </Body>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}

          {/* Help */}
          <div style={{ marginTop: 40, textAlign: 'center' }}>
            <Body small style={{ color: c.gray }}>
              Questions about your order? Email <a href="mailto:hello@jagtarstudio.com" style={{ color: c.charcoal }}>hello@jagtarstudio.com</a>
            </Body>
          </div>
        </div>
      </Section>
    </div>
  );
};

Object.assign(window, { JagtarAccount });
