/* =========================================================
   Auth — Login, Signup, Account dashboard
   ========================================================= */

const { useState: useAuthState, useEffect: useAuthEffect } = React;

const USER_KEY = 'clarion_user';

function getUser() {
  try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); } catch { return null; }
}
function setUser(u) {
  if (u) localStorage.setItem(USER_KEY, JSON.stringify(u));
  else localStorage.removeItem(USER_KEY);
  window.dispatchEvent(new CustomEvent('clarion-user-change'));
}
function useUser() {
  const [u, setU] = useAuthState(getUser);
  useAuthEffect(() => {
    const sync = () => setU(getUser());
    window.addEventListener('clarion-user-change', sync);
    window.addEventListener('storage', sync);
    return () => { window.removeEventListener('clarion-user-change', sync); window.removeEventListener('storage', sync); };
  }, []);
  return u;
}

const authInput = { width: '100%', padding: '11px 14px', border: '1px solid var(--border-strong)', borderRadius: 8, fontSize: 14, fontFamily: 'var(--font-sans)', color: 'var(--fg-brand)', background: '#fff' };

function AuthShell({ eyebrow, title, subtitle, children, side }) {
  return (
    <section style={{ padding: '56px 0 96px' }}>
      <div className="container" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'center' }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>{eyebrow}</div>
          <h1 style={{ fontSize: 44, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: '0 0 12px', lineHeight: 1.05 }}>{title}</h1>
          {subtitle && <p style={{ fontSize: 15, color: 'var(--fg1)', lineHeight: 1.65, marginBottom: 32, maxWidth: 460 }}>{subtitle}</p>}
          {children}
        </div>
        <div className="auth-side">{side}</div>
      </div>
    </section>
  );
}

function LoginPage({ go }) {
  const [email, setEmail] = useAuthState('');
  const [password, setPassword] = useAuthState('');
  const [err, setErr] = useAuthState('');
  const submit = (e) => {
    e.preventDefault();
    if (!email.includes('@')) return setErr('Enter a valid email.');
    if (password.length < 6) return setErr('Password must be at least 6 characters.');
    setUser({ email, name: email.split('@')[0], joined: new Date().toISOString() });
    go('account');
  };
  return (
    <AuthShell
      eyebrow="SIGN IN"
      title="Welcome back."
      subtitle="Sign in to track orders, download COAs, and re-order faster."
      side={<AuthSideReassurance />}
    >
      <form onSubmit={submit}>
        {err && <div className="auth-err">{err}</div>}
        <label style={{ display: 'block', marginBottom: 16 }}>
          <div className="checkout-field-label">EMAIL</div>
          <input style={authInput} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@institution.edu" required />
        </label>
        <label style={{ display: 'block', marginBottom: 10 }}>
          <div className="checkout-field-label">PASSWORD</div>
          <input style={authInput} type="password" value={password} onChange={e => setPassword(e.target.value)} required />
        </label>
        <div style={{ textAlign: 'right', marginBottom: 20 }}>
          <a className="btn-link" style={{ fontSize: 12 }}>Forgot password?</a>
        </div>
        <button className="btn btn-primary" type="submit" style={{ width: '100%' }}>Sign in →</button>
        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 13, color: 'var(--fg2)' }}>
          New to Clarion? <a className="btn-link" onClick={() => go('signup')}>Create an account</a>
        </div>
      </form>
    </AuthShell>
  );
}

function SignupPage({ go }) {
  const [form, setForm] = useAuthState({ name: '', email: '', password: '', institution: '', attest: false });
  const [err, setErr] = useAuthState('');
  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = (e) => {
    e.preventDefault();
    if (!form.attest) return setErr('Please confirm the research-use attestation.');
    if (!form.email.includes('@')) return setErr('Enter a valid email.');
    if (form.password.length < 6) return setErr('Password must be at least 6 characters.');
    setUser({ email: form.email, name: form.name, institution: form.institution, joined: new Date().toISOString() });
    go('account');
  };
  return (
    <AuthShell
      eyebrow="CREATE ACCOUNT"
      title="Start researching."
      subtitle="Accounts let you track orders, re-order from history, and store COAs in one place."
      side={<AuthSideReassurance />}
    >
      <form onSubmit={submit}>
        {err && <div className="auth-err">{err}</div>}
        <div className="checkout-grid">
          <label style={{ display: 'block', gridColumn: '1/-1' }}><div className="checkout-field-label">FULL NAME</div><input style={authInput} required value={form.name} onChange={e => upd('name', e.target.value)} /></label>
          <label style={{ display: 'block', gridColumn: '1/-1' }}><div className="checkout-field-label">INSTITUTION (OPTIONAL)</div><input style={authInput} value={form.institution} onChange={e => upd('institution', e.target.value)} /></label>
          <label style={{ display: 'block', gridColumn: '1/-1' }}><div className="checkout-field-label">EMAIL</div><input type="email" style={authInput} required value={form.email} onChange={e => upd('email', e.target.value)} /></label>
          <label style={{ display: 'block', gridColumn: '1/-1' }}><div className="checkout-field-label">PASSWORD</div><input type="password" style={authInput} required value={form.password} onChange={e => upd('password', e.target.value)} /></label>
        </div>
        <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', margin: '20px 0', padding: 14, background: 'var(--clarion-frost)', border: '1px solid var(--border-strong)', borderRadius: 8 }}>
          <input type="checkbox" checked={form.attest} onChange={e => upd('attest', e.target.checked)} style={{ marginTop: 3 }} />
          <span style={{ fontSize: 12, lineHeight: 1.6, color: 'var(--fg1)' }}>
            I confirm I am a qualified researcher, and all compounds purchased will be used <strong>for research purposes only</strong>, never for human or veterinary consumption.
          </span>
        </label>
        <button className="btn btn-primary" type="submit" style={{ width: '100%' }}>Create account →</button>
        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 13, color: 'var(--fg2)' }}>
          Already have an account? <a className="btn-link" onClick={() => go('login')}>Sign in</a>
        </div>
      </form>
    </AuthShell>
  );
}

function AuthSideReassurance() {
  return (
    <div className="auth-side-card">
      <div className="eyebrow eyebrow-mint" style={{ marginBottom: 18 }}>WHAT YOU GET</div>
      <ul className="auth-side-list">
        <li><span>01</span><div><strong>Order history & re-order</strong><br/>Every past order one click away.</div></li>
        <li><span>02</span><div><strong>COA archive</strong><br/>Lot-specific certificates stored permanently.</div></li>
        <li><span>03</span><div><strong>Shipment tracking</strong><br/>Live tracking on every order.</div></li>
        <li><span>04</span><div><strong>Priority support</strong><br/>Direct line to our analytical team.</div></li>
      </ul>
    </div>
  );
}

function AccountPage({ go }) {
  const user = useUser();
  if (!user) {
    return (
      <section style={{ padding: '96px 0' }}>
        <div className="container-narrow" style={{ textAlign: 'center' }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>ACCOUNT</div>
          <h1 style={{ fontSize: 36, fontWeight: 900, color: 'var(--fg-brand)', margin: '0 0 16px' }}>Not signed in</h1>
          <p style={{ color: 'var(--fg2)', marginBottom: 24 }}>Sign in to view your orders, COAs, and addresses.</p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 12 }}>
            <button className="btn btn-ghost" onClick={() => go('signup')}>Create account</button>
            <button className="btn btn-primary" onClick={() => go('login')}>Sign in →</button>
          </div>
        </div>
      </section>
    );
  }
  let orders = [];
  try { orders = JSON.parse(localStorage.getItem('clarion_orders_' + user.email) || '[]'); } catch {}
  return (
    <section style={{ padding: '56px 0 96px' }}>
      <div className="container">
        <div className="eyebrow" style={{ marginBottom: 14 }}>ACCOUNT</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40, flexWrap: 'wrap', gap: 16 }}>
          <h1 style={{ fontSize: 44, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: 0 }}>Hello, {user.name || user.email.split('@')[0]}.</h1>
          <button className="btn btn-ghost" onClick={() => { setUser(null); go('home'); }}>Sign out</button>
        </div>

        <div className="account-grid">
          <aside className="account-side">
            <div className="account-profile">
              <div className="account-avatar">{(user.name || user.email)[0].toUpperCase()}</div>
              <div>
                <div style={{ fontWeight: 700, color: 'var(--fg-brand)' }}>{user.name || 'Researcher'}</div>
                <div style={{ fontSize: 12, color: 'var(--fg2)' }}>{user.email}</div>
                {user.institution && <div style={{ fontSize: 12, color: 'var(--fg2)', marginTop: 2 }}>{user.institution}</div>}
              </div>
            </div>
            <nav className="account-nav">
              <a className="is-active">Orders</a>
              <a>Addresses</a>
              <a>Payment methods</a>
              <a>COA archive</a>
              <a>Notifications</a>
            </nav>
          </aside>

          <div>
            <h3 className="account-section-title">Order history</h3>
            {orders.length === 0 ? (
              <div className="account-empty">
                <div style={{ fontSize: 15, color: 'var(--fg1)', marginBottom: 16 }}>No orders yet. When you place one, it'll appear here with COAs and tracking.</div>
                <button className="btn btn-primary" onClick={() => go('catalog')}>Browse catalog →</button>
              </div>
            ) : (
              <div className="account-orders">
                {orders.map(o => (
                  <div key={o.orderNum} className="account-order">
                    <div className="account-order-head">
                      <div>
                        <div className="cart-line-cat">{new Date(o.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
                        <div className="account-order-num">{o.orderNum}</div>
                      </div>
                      <div className="account-order-status">In transit</div>
                      <div className="account-order-total">{fmt2(o.total)}</div>
                    </div>
                    <div className="account-order-items">
                      {o.lines.map(l => (
                        <div key={l.slug} className="account-order-item">
                          <img src="./assets/vial-photo.webp" alt="" />
                          <div>
                            <div style={{ fontWeight: 700, color: 'var(--fg-brand)', fontSize: 14 }}>{l.code}</div>
                            <div style={{ fontSize: 12, color: 'var(--fg2)', fontFamily: 'var(--font-mono)' }}>{l.weight} · Qty {l.qty}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                    <div className="account-order-actions">
                      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg2)', letterSpacing: '.08em' }}>TRACKING: {o.tracking}</span>
                      <div style={{ display: 'flex', gap: 8 }}>
                        <button className="btn btn-ghost" style={{ padding: '7px 14px', fontSize: 12 }}>Download COAs</button>
                        <button className="btn btn-primary" style={{ padding: '7px 14px', fontSize: 12 }} onClick={() => {
                          // re-order: add all items to cart
                          try {
                            const cart = JSON.parse(localStorage.getItem('clarion_cart') || '[]');
                            for (const l of o.lines) {
                              const found = cart.find(i => i.slug === l.slug);
                              if (found) found.qty = Math.min(99, found.qty + l.qty);
                              else cart.push({ slug: l.slug, qty: l.qty });
                            }
                            localStorage.setItem('clarion_cart', JSON.stringify(cart));
                            window.dispatchEvent(new CustomEvent('clarion-cart-change'));
                            go('cart');
                          } catch {}
                        }}>Re-order</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { getUser, setUser, useUser, LoginPage, SignupPage, AccountPage });
