// Dashboard page — user info, subscriptions, alerts, settings

const DashboardPage = () => {
  const [user, setUser] = React.useState(null);
  const [subs, setSubs] = React.useState([]);
  const [alerts, setAlerts] = React.useState([]);
  const [prefs, setPrefs] = React.useState({ digest_frequency: 'immediate', timezone: 'UTC' });
  const [prefSaved, setPrefSaved] = React.useState(false);
  const [loading, setLoading] = React.useState(true);
  const [authError, setAuthError] = React.useState(false);

  // Login form state
  const [showLogin, setShowLogin] = React.useState(false);
  const [loginEmail, setLoginEmail] = React.useState('');
  const [loginPass, setLoginPass] = React.useState('');
  const [loginError, setLoginError] = React.useState('');
  const [signupMode, setSignupMode] = React.useState(false);

  const token = typeof localStorage !== 'undefined' ? localStorage.getItem('fp_token') : null;

  React.useEffect(() => {
    if (!token) { setShowLogin(true); setLoading(false); return; }
    loadDashboard();
  }, []);

  async function loadDashboard() {
    try {
      const me = await fhFetch('/auth/me');
      setUser(me.user);
      setSubs(me.subscriptions || []);
      if (me.preferences) setPrefs(me.preferences);

      try {
        const alertData = await fhFetch('/alerts?limit=20');
        setAlerts(alertData || []);
      } catch {}
    } catch {
      localStorage.removeItem('fp_token');
      setAuthError(true);
      setShowLogin(true);
    }
    setLoading(false);
  }

  async function handleLogin(e) {
    e.preventDefault();
    setLoginError('');
    const endpoint = signupMode ? '/auth/signup' : '/auth/login';
    try {
      const res = await fetch(FH_API + endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: loginEmail, password: loginPass }),
      });
      const data = await res.json();
      if (data.token) {
        localStorage.setItem('fp_token', data.token);
        setShowLogin(false);
        setLoading(true);
        loadDashboard();
      } else {
        setLoginError(data.error || 'Authentication failed');
      }
    } catch {
      setLoginError('Network error');
    }
  }

  async function updatePrefs(field, value) {
    const next = { ...prefs, [field]: value };
    setPrefs(next);
    try {
      await fhFetch('/auth/preferences', {
        method: 'PUT',
        body: JSON.stringify({ digest_frequency: next.digest_frequency, timezone: next.timezone }),
      });
      setPrefSaved(true);
      setTimeout(() => setPrefSaved(false), 2000);
    } catch {}
  }

  async function cancelSub(subId) {
    if (!confirm('Cancel this subscription?')) return;
    try {
      await fhFetch('/billing/cancel', {
        method: 'POST',
        body: JSON.stringify({ subscriptionId: subId }),
      });
      loadDashboard();
    } catch { alert('Failed to cancel'); }
  }

  async function exportAlerts() {
    try {
      const token = localStorage.getItem('fp_token');
      const res = await fetch(FH_API + '/alerts/export', {
        headers: { 'Authorization': 'Bearer ' + token },
      });
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = 'firmhound-alerts.csv'; a.click();
      URL.revokeObjectURL(url);
    } catch { alert('Export failed'); }
  }

  function logout() {
    localStorage.removeItem('fp_token');
    window.location.href = 'index.html';
  }

  // Login / Signup form
  if (showLogin) {
    return (
      <PageShell active={null}>
        <div style={{ padding: '80px 32px', maxWidth: 420, margin: '0 auto' }}>
          <div style={{ fontSize: 11, color: FH.ink3, letterSpacing: '0.18em', marginBottom: 18 }}>
            ◆ {signupMode ? 'CREATE ACCOUNT' : 'SIGN IN'}
          </div>
          <div style={{
            fontFamily: '"Instrument Serif", Georgia, serif',
            fontSize: 48, lineHeight: 1, marginBottom: 28,
          }}>
            {signupMode ? 'Get started.' : 'Welcome back.'}
          </div>
          {loginError && (
            <div style={{ padding: '10px 14px', background: 'rgba(255,80,60,0.1)', border: `1px solid ${FH.red}`, color: FH.red, fontSize: 12, marginBottom: 16 }}>
              {loginError}
            </div>
          )}
          <form onSubmit={handleLogin}>
            <div style={{ marginBottom: 16 }}>
              <label style={{ fontSize: 10, color: FH.ink3, letterSpacing: '0.14em', display: 'block', marginBottom: 6 }}>EMAIL</label>
              <input type="email" value={loginEmail} onChange={e => setLoginEmail(e.target.value)} required style={{
                width: '100%', padding: '12px 14px', background: FH.bg2, border: `1px solid ${FH.border}`,
                color: FH.ink, fontFamily: '"JetBrains Mono", monospace', fontSize: 13, outline: 'none',
              }} />
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={{ fontSize: 10, color: FH.ink3, letterSpacing: '0.14em', display: 'block', marginBottom: 6 }}>PASSWORD</label>
              <input type="password" value={loginPass} onChange={e => setLoginPass(e.target.value)} required style={{
                width: '100%', padding: '12px 14px', background: FH.bg2, border: `1px solid ${FH.border}`,
                color: FH.ink, fontFamily: '"JetBrains Mono", monospace', fontSize: 13, outline: 'none',
              }} />
            </div>
            <button type="submit" style={{
              width: '100%', padding: '14px', background: FH.accent, color: FH.bg,
              border: 'none', fontSize: 12, letterSpacing: '0.12em', fontWeight: 600,
              cursor: 'pointer', fontFamily: '"JetBrains Mono", monospace',
            }}>
              {signupMode ? 'CREATE ACCOUNT' : 'SIGN IN'} ↗
            </button>
          </form>
          <div style={{ marginTop: 20, fontSize: 12, color: FH.ink3, textAlign: 'center' }}>
            {signupMode ? 'Already have an account?' : "Don't have an account?"}{' '}
            <span onClick={() => { setSignupMode(!signupMode); setLoginError(''); }}
              style={{ color: FH.accent, cursor: 'pointer' }}>
              {signupMode ? 'Sign in' : 'Sign up'}
            </span>
          </div>
          <div style={{ marginTop: 12, textAlign: 'center' }}>
            <a href="reset.html" style={{ fontSize: 11, color: FH.ink3, textDecoration: 'none' }}>Forgot password?</a>
          </div>
        </div>
      </PageShell>
    );
  }

  if (loading) {
    return (
      <PageShell active={null}>
        <div style={{ padding: '80px 32px', textAlign: 'center', color: FH.ink3, fontSize: 13 }}>
          Loading...
        </div>
      </PageShell>
    );
  }

  return (
    <PageShell active={null}>
      {/* Dashboard header */}
      <div style={{
        padding: '32px 32px 24px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        borderBottom: `1px solid ${FH.border}`,
      }}>
        <div>
          <div style={{ fontSize: 11, color: FH.ink3, letterSpacing: '0.18em', marginBottom: 8 }}>
            ◆ DASHBOARD
          </div>
          <div style={{
            fontFamily: '"Instrument Serif", Georgia, serif',
            fontSize: 36, lineHeight: 1,
          }}>
            {user ? user.email : 'Dashboard'}
          </div>
          <div style={{ fontSize: 12, color: FH.ink3, marginTop: 8 }}>
            {subs.length} active subscription{subs.length !== 1 ? 's' : ''}
          </div>
        </div>
        <span onClick={logout} style={{
          fontSize: 11, color: FH.ink3, letterSpacing: '0.12em', cursor: 'pointer',
          padding: '6px 14px', border: `1px solid ${FH.border}`,
        }}>
          LOGOUT
        </span>
      </div>

      {/* Subscriptions */}
      <div style={{ padding: '32px 32px' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          borderBottom: `1.5px solid ${FH.borderHi}`, paddingBottom: 10, marginBottom: 4,
        }}>
          <div style={{ fontSize: 12, color: FH.ink, letterSpacing: '0.14em', fontWeight: 600 }}>
            ◆ SUBSCRIPTIONS
          </div>
          <div style={{ fontSize: 10, color: FH.ink3, letterSpacing: '0.1em' }}>
            {subs.length} ACTIVE
          </div>
        </div>
        {subs.length === 0 ? (
          <div style={{ padding: '24px 0', color: FH.ink3, fontSize: 13 }}>
            No active subscriptions.{' '}
            <a href="index.html#portfolio" style={{ color: FH.accent, textDecoration: 'none' }}>Browse products ↗</a>
          </div>
        ) : subs.map(s => (
          <div key={s.id} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '16px 0', borderBottom: `1px solid ${FH.border}`,
          }}>
            <div>
              <div style={{ color: FH.ink, fontWeight: 500, fontSize: 14 }}>{s.product_name}</div>
              <div style={{ color: FH.ink3, fontSize: 11, marginTop: 2 }}>{s.plan || 'Monthly'}</div>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <span style={{
                fontSize: 10, padding: '3px 8px', letterSpacing: '0.1em',
                color: s.status === 'active' ? FH.accent : FH.red,
                border: `1px solid ${s.status === 'active' ? FH.accent : FH.red}`,
              }}>
                {s.status ? s.status.toUpperCase() : 'ACTIVE'}
              </span>
              {s.status === 'active' && (
                <span onClick={() => cancelSub(s.id)} style={{
                  fontSize: 10, color: FH.ink3, cursor: 'pointer', letterSpacing: '0.1em',
                  padding: '3px 8px', border: `1px solid ${FH.border}`,
                }}>CANCEL</span>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Alerts */}
      <div style={{ padding: '0 32px 32px' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          borderBottom: `1.5px solid ${FH.borderHi}`, paddingBottom: 10, marginBottom: 4,
        }}>
          <div style={{ fontSize: 12, color: FH.ink, letterSpacing: '0.14em', fontWeight: 600 }}>
            ◆ RECENT ALERTS
          </div>
          <span onClick={exportAlerts} style={{
            fontSize: 10, color: FH.ink3, letterSpacing: '0.1em', cursor: 'pointer',
            padding: '3px 10px', border: `1px solid ${FH.border}`,
          }}>EXPORT CSV</span>
        </div>
        {alerts.length === 0 ? (
          <div style={{ padding: '24px 0', color: FH.ink3, fontSize: 13 }}>
            No alerts yet. Subscribe to a product to start receiving alerts.
          </div>
        ) : alerts.map((a, i) => (
          <div key={i} style={{ padding: '16px 0', borderBottom: `1px solid ${FH.border}` }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <span style={{
                  fontSize: 9, color: FH.ink3, letterSpacing: '0.12em', padding: '2px 6px',
                  border: `1px solid ${FH.border}`, textTransform: 'uppercase',
                }}>{a.product_name}</span>
                <span style={{ color: FH.ink, fontWeight: 500, fontSize: 14 }}>{a.title}</span>
              </div>
              <span style={{ color: FH.ink3, fontSize: 11 }}>
                {a.created_at ? new Date(a.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : ''}
              </span>
            </div>
            <div style={{ color: FH.ink2, fontSize: 12, lineHeight: 1.55, paddingLeft: 0 }}>
              {(a.enriched_content || a.content || '').slice(0, 200)}
              {(a.enriched_content || a.content || '').length >= 200 ? '...' : ''}
            </div>
          </div>
        ))}
      </div>

      {/* Settings */}
      <div style={{
        padding: '32px', background: FH.bg2,
        borderTop: `1px solid ${FH.border}`,
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          borderBottom: `1.5px solid ${FH.borderHi}`, paddingBottom: 10, marginBottom: 24,
        }}>
          <div style={{ fontSize: 12, color: FH.ink, letterSpacing: '0.14em', fontWeight: 600 }}>
            ◆ SETTINGS
          </div>
          {prefSaved && <span style={{ fontSize: 10, color: FH.accent, letterSpacing: '0.1em' }}>SAVED</span>}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          <div>
            <div style={{ fontSize: 12, color: FH.ink, fontWeight: 500, marginBottom: 4 }}>Email frequency</div>
            <div style={{ fontSize: 11, color: FH.ink3, marginBottom: 10 }}>How often you receive alert digests</div>
            <select value={prefs.digest_frequency} onChange={e => updatePrefs('digest_frequency', e.target.value)} style={{
              width: '100%', padding: '10px 12px', background: FH.bg, border: `1px solid ${FH.border}`,
              color: FH.ink, fontFamily: '"JetBrains Mono", monospace', fontSize: 12,
            }}>
              <option value="immediate">Immediate</option>
              <option value="daily">Daily digest</option>
              <option value="weekly">Weekly digest</option>
            </select>
          </div>
          <div>
            <div style={{ fontSize: 12, color: FH.ink, fontWeight: 500, marginBottom: 4 }}>Timezone</div>
            <div style={{ fontSize: 11, color: FH.ink3, marginBottom: 10 }}>For scheduling daily/weekly digests</div>
            <select value={prefs.timezone} onChange={e => updatePrefs('timezone', e.target.value)} style={{
              width: '100%', padding: '10px 12px', background: FH.bg, border: `1px solid ${FH.border}`,
              color: FH.ink, fontFamily: '"JetBrains Mono", monospace', fontSize: 12,
            }}>
              <option value="UTC">UTC</option>
              <option value="America/New_York">Eastern</option>
              <option value="America/Chicago">Central</option>
              <option value="America/Denver">Mountain</option>
              <option value="America/Los_Angeles">Pacific</option>
              <option value="Europe/London">London</option>
              <option value="Europe/Berlin">Berlin</option>
              <option value="Asia/Tokyo">Tokyo</option>
            </select>
          </div>
        </div>
      </div>
    </PageShell>
  );
};

window.DashboardPage = DashboardPage;
