// upprofiler — /account
// Magic-link login + score history timeline + manage subscription.

function PageAccount({ onNavigate, score: globalScore }) {
  const [bootstrap, setBootstrap] = useState({ status: 'loading' }); // loading | signed-out | signed-in | error
  const [email, setEmail] = useState('');
  const [sending, setSending] = useState(false);
  const [sendErr, setSendErr] = useState('');
  const [sentTo, setSentTo] = useState('');
  const [signingOut, setSigningOut] = useState(false);

  // Initial fetch of history (which doubles as a session check).
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const resp = await fetch('/api/history', { credentials: 'include' });
        if (cancelled) return;
        if (resp.status === 401) {
          setBootstrap({ status: 'signed-out' });
          return;
        }
        if (!resp.ok) {
          setBootstrap({ status: 'error', message: 'Could not load your account.' });
          return;
        }
        const data = await resp.json();
        setBootstrap({ status: 'signed-in', ...data });
      } catch (e) {
        if (cancelled) return;
        setBootstrap({ status: 'error', message: 'Network hiccup. Refresh to try again.' });
      }
    })();
    return () => { cancelled = true; };
  }, []);

  async function sendMagicLink(e) {
    if (e && e.preventDefault) e.preventDefault();
    const v = email.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) {
      setSendErr("That doesn't look like an email.");
      return;
    }
    setSendErr('');
    setSending(true);
    try {
      const resp = await fetch('/api/auth/sign-in/magic-link', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: v,
          callbackURL: `${window.location.origin}/#/account`,
        }),
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok) {
        setSendErr(data?.message || 'Could not send the magic link. Try again.');
        return;
      }
      setSentTo(v);
    } catch (err) {
      setSendErr('Network hiccup. Try again.');
    } finally {
      setSending(false);
    }
  }

  async function signOut() {
    setSigningOut(true);
    try {
      await fetch('/api/auth/sign-out', {
        method: 'POST',
        credentials: 'include',
      });
      setBootstrap({ status: 'signed-out' });
      setEmail('');
      setSentTo('');
    } catch (err) {
      // No-op; user can refresh
    } finally {
      setSigningOut(false);
    }
  }

  return (
    <div>
      <Nav current="/account" onNavigate={onNavigate} score={globalScore} delta={9} />
      <div className="page">
        <PageHeader
          id="/account"
          name="Your account"
          sub={bootstrap.status === 'signed-in'
            ? 'Your score history and subscription. Re-score any profile to add a new entry.'
            : 'Sign in with a magic link to see your score history and manage monthly re-scores.'}
          tag={{ kind: 'pink', label: bootstrap.status === 'signed-in' ? 'Signed in' : 'Sign in' }}
        />

        {bootstrap.status === 'loading' && (
          <Card title="Loading…" id="/account/loading">
            <div className="muted">Reading your session.</div>
          </Card>
        )}

        {bootstrap.status === 'error' && (
          <Card title="Hit a snag" id="/account/error">
            <div className="muted">{bootstrap.message}</div>
          </Card>
        )}

        {bootstrap.status === 'signed-out' && !sentTo && (
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 24 }}>
            <Card title="Sign in" id="/account/sign-in" tag={{ kind: 'pink', label: 'Magic link' }}>
              <p style={{ color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.55, marginBottom: 20 }}>
                One email. One tap. No passwords, no friction. We'll send a link that signs you in for 30 days.
              </p>
              <form onSubmit={sendMagicLink}>
                <div style={{
                  display: 'flex', gap: 8,
                  background: 'var(--surface)',
                  border: `1px solid ${sendErr ? 'var(--warn)' : 'var(--line)'}`,
                  borderRadius: 10, padding: 5,
                  boxShadow: 'var(--shadow-card)',
                }}>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); if (sendErr) setSendErr(''); }}
                    placeholder="you@email.com"
                    autoComplete="email"
                    style={{
                      flex: 1, padding: '12px 14px', fontSize: 15,
                      fontFamily: 'var(--font-display)',
                      border: 'none', background: 'transparent',
                      color: 'var(--ink)', outline: 'none',
                    }}
                  />
                  <button type="submit" className="btn btn-primary" disabled={sending} style={{ padding: '10px 22px', fontSize: 14 }}>
                    {sending ? 'Sending…' : 'Send magic link →'}
                  </button>
                </div>
                {sendErr && <div className="label-mono" style={{ color: 'var(--warn)', marginTop: 10 }}>{sendErr}</div>}
              </form>
            </Card>

            <Card title="What signing in unlocks" id="/account/why">
              <ul style={{ paddingLeft: 0, margin: 0, listStyle: 'none' }}>
                {[
                  ['Score history', 'Every profile you score gets logged here, so you can watch your number move over time.'],
                  ['Monthly re-scores', 'We re-check your profile + last 30 days each month and email you the new number.'],
                  ['Unsubscribe management', 'One-click off. We hold no grudges.'],
                ].map(([t, d]) => (
                  <li key={t} className="row gap-12" style={{ alignItems: 'flex-start', marginBottom: 14 }}>
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0, marginTop: 2 }}>
                      <circle cx="8" cy="8" r="7.5" stroke="var(--pink)" strokeWidth="1.4" fill="none" />
                      <path d="M5 8 L7 10 L11 6" stroke="var(--pink)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
                    </svg>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{t}</div>
                      <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 2, lineHeight: 1.5 }}>{d}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </Card>
          </div>
        )}

        {bootstrap.status === 'signed-out' && sentTo && (
          <Card title="Check your inbox" id="/account/sent" tag={{ kind: 'good', label: '✓ Sent' }}>
            <p style={{ fontSize: 16, color: 'var(--ink)' }}>
              Magic link on its way to <strong>{sentTo}</strong>.
            </p>
            <p style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 10, lineHeight: 1.55 }}>
              It expires in 5 minutes. Tap the link on this device to keep your session here.
            </p>
            <button className="btn btn-tertiary btn-sm" style={{ marginTop: 16 }} onClick={() => { setSentTo(''); }}>
              Use a different email
            </button>
          </Card>
        )}

        {bootstrap.status === 'signed-in' && (
          <SignedInView data={bootstrap} onNavigate={onNavigate} onSignOut={signOut} signingOut={signingOut} />
        )}
      </div>
      <Footer />
    </div>
  );
}

function SignedInView({ data, onNavigate, onSignOut, signingOut }) {
  const { user, scores, subscription } = data;
  const latest = scores[0] || null;

  function bandFor(score) {
    if (score >= 85) return { label: 'Convinced', color: 'var(--good)' };
    if (score >= 70) return { label: 'Aligned',   color: 'var(--good)' };
    if (score >= 55) return { label: 'Mixed',     color: 'var(--warn)' };
    if (score >= 40) return { label: 'Drifting',  color: 'var(--warn)' };
    return { label: 'Off-brand', color: 'var(--warn)' };
  }

  function timeAgo(iso) {
    if (!iso) return '';
    const ts = new Date(iso).getTime();
    const s = Math.floor((Date.now() - ts) / 1000);
    if (s < 60) return `${s}s ago`;
    if (s < 3600) return `${Math.floor(s / 60)}m ago`;
    if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
    if (s < 604800) return `${Math.floor(s / 86400)}d ago`;
    return new Date(iso).toLocaleDateString();
  }

  return (
    <>
      {/* Account header card */}
      <Card id="/account/me" title={`Welcome${user.name ? `, ${user.name.split(' ')[0]}` : ''}`} tag={{ kind: 'pink', label: user.email }}>
        <div className="row between" style={{ alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <div style={{ color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.5, maxWidth: '60ch' }}>
            {latest
              ? <>Your most recent conviction score was <strong style={{ color: 'var(--pink)' }}>{latest.score}</strong> ({timeAgo(latest.scored_at)}).</>
              : <>No scores yet. Paste a LinkedIn profile on the homepage to add your first one.</>
            }
          </div>
          <div className="row gap-8">
            <button className="btn btn-secondary btn-sm" onClick={() => onNavigate('/')}>Score another →</button>
            <button className="btn btn-tertiary btn-sm" onClick={onSignOut} disabled={signingOut}>
              {signingOut ? 'Signing out…' : 'Sign out'}
            </button>
          </div>
        </div>
      </Card>

      {/* Subscription state */}
      {subscription && (
        <Card id="/account/subscription" title="Monthly re-scores" tag={{
          kind: subscription.unsubscribed_at ? 'warn' : 'good',
          label: subscription.unsubscribed_at ? 'Off' : 'On',
        }} style={{ marginTop: 16 }}>
          <div style={{ fontSize: 15, color: 'var(--ink-soft)', lineHeight: 1.6, marginBottom: 12 }}>
            {subscription.unsubscribed_at
              ? <>You're unsubscribed from monthly re-scores. Score any profile again and we'll re-enable it.</>
              : <>We re-check <strong>{subscription.linkedin_url}</strong> on the 1st of each month and email the new score to <strong>{user.email}</strong>.</>
            }
          </div>
          {subscription.last_score != null && (
            <div className="row gap-24" style={{ paddingTop: 12, borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
              <div>
                <div className="label-mono">Last score</div>
                <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--pink)', letterSpacing: '-0.5px', marginTop: 2 }}>
                  {subscription.last_score}
                </div>
              </div>
              {subscription.last_scored_at && (
                <div>
                  <div className="label-mono">Scored</div>
                  <div style={{ fontSize: 14, fontWeight: 600, marginTop: 6 }}>{timeAgo(subscription.last_scored_at)}</div>
                </div>
              )}
            </div>
          )}
        </Card>
      )}

      {/* Score history timeline */}
      <Card id="/account/history" title="Score history" tag={{ label: `${scores.length} score${scores.length === 1 ? '' : 's'}` }} style={{ marginTop: 16 }}>
        {scores.length === 0 ? (
          <div style={{ color: 'var(--ink-soft)', padding: '12px 0' }}>
            Score a profile to start your timeline. Every score you trigger from this account shows up here.
            <div style={{ marginTop: 16 }}>
              <button className="btn btn-primary btn-sm" onClick={() => onNavigate('/')}>Score your first profile →</button>
            </div>
          </div>
        ) : (
          <div className="col gap-8" style={{ marginTop: 6 }}>
            {scores.map((s) => {
              const band = bandFor(s.score);
              const handle = (s.linkedin_url || '').match(/in\/([^/?#]+)/)?.[1] || s.linkedin_url;
              return (
                <div key={s.id} className="row gap-16" style={{
                  padding: '14px 16px',
                  borderRadius: 8,
                  border: '1px solid var(--line)',
                  alignItems: 'center',
                }}>
                  {s.profile_photo ? (
                    <img src={s.profile_photo} alt="" width={40} height={40}
                      referrerPolicy="no-referrer"
                      style={{ width: 40, height: 40, borderRadius: 40, objectFit: 'cover', flexShrink: 0 }} />
                  ) : (
                    <div className="nav-avatar" style={{ width: 40, height: 40, fontSize: 14, flexShrink: 0 }}>
                      {(s.profile_name || handle || '?').split(' ').map(n => n[0]).slice(0, 2).join('')}
                    </div>
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14, letterSpacing: '-0.01em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {s.profile_name || handle}
                    </div>
                    <div className="label-mono" style={{ marginTop: 2 }}>
                      {timeAgo(s.scored_at)}
                      {s.alignment_pct != null && ` · ${s.alignment_pct}% aligned`}
                      {s.source === 'cron' && ' · auto re-score'}
                    </div>
                  </div>
                  <div className="row gap-12" style={{ alignItems: 'center' }}>
                    <span style={{
                      fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
                      color: band.color, letterSpacing: 1.2, textTransform: 'uppercase',
                    }}>
                      {band.label}
                    </span>
                    <div style={{
                      fontSize: 28, fontWeight: 800, color: band.color,
                      letterSpacing: '-0.5px', minWidth: 48, textAlign: 'right',
                      fontVariantNumeric: 'tabular-nums',
                    }}>
                      {s.score}
                    </div>
                    <button className="btn btn-tertiary btn-sm" style={{ padding: '4px 10px', fontSize: 11 }}
                      onClick={() => onNavigate(`/score?url=${encodeURIComponent(s.linkedin_url)}`)}>
                      Open →
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </>
  );
}

window.PageAccount = PageAccount;
