// auth.jsx — creator authentication screens: sign up / log in / forgot-password
// / email-confirmation, backed by Supabase email+password auth.
//
// The session store itself lives in supabase-client.js (window.MBAuth, also
// exposed as window.DripcheckAuth for the existing call sites). This file is
// the UI layer plus the calls into that store.
//
// Account states are now real rather than simulated:
//   sign up  → Supabase creates the user. If the project requires email
//              confirmation there is no session yet, so we show the "confirm
//              your email" screen. Otherwise the user is signed straight in.
//   log in   → signInWithPassword. Supabase rejects unconfirmed accounts.
//   log out  → signOut, clearing the persisted session.

const { useState: useStateAU, useEffect: useEffectAU } = React;

// React hook — subscribes to session changes emitted by supabase-client.js.
function useSession() {
  const [session, setSession] = useStateAU(() => MBAuth.get());
  useEffectAU(() => {
    const sync = () => setSession(MBAuth.get());
    window.addEventListener('dripcheck-session', sync);
    window.addEventListener('storage', sync);
    sync();
    return () => {
      window.removeEventListener('dripcheck-session', sync);
      window.removeEventListener('storage', sync);
    };
  }, []);
  return session;
}
window.useSession = useSession;

// ─── Shared editorial split layout ──────────────────────────────────────────
function AuthLayout({ children, footer }) {
  const { OUTFITS } = window.DRIPCHECK_DATA;
  const showcase = OUTFITS.slice(0, 6);
  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
      {/* Left editorial half */}
      <div style={{
        padding: 56, background: '#F2EFE7', position: 'relative', overflow: 'hidden',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      }} className="dc-auth-aside">
        <button onClick={() => window.__dripcheckGo?.({ name: 'home' })} style={{ appearance: 'none', border: 'none', background: 'transparent', padding: 0, cursor: 'pointer', alignSelf: 'flex-start' }}>
          <Logo size={20}/>
        </button>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#5a5550' }}>Creator Studio · Vol. 04</div>
          <h1 style={{ marginTop: 16, fontSize: 'clamp(36px, 4vw, 60px)', lineHeight: 0.98, letterSpacing: '-0.03em', fontWeight: 400, color: '#1a1a18' }}>
            Turn your style<br/>into a <em style={{ fontFamily: "'Instrument Serif',serif", fontStyle: 'italic' }}>shoppable</em><br/>archive.
          </h1>
          <p style={{ marginTop: 18, fontSize: 15, color: '#3a3a36', maxWidth: '38ch', lineHeight: 1.55 }}>
            Create outfits, tag products, track clicks, and earn affiliate revenue from your wardrobe.
          </p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, opacity: 0.95 }}>
          {showcase.map(o => (
            <div key={o.id} style={{ aspectRatio: '1 / 1', borderRadius: 10, overflow: 'hidden', background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.05)' }}>
              <OutfitBoard outfit={o}/>
            </div>
          ))}
        </div>
      </div>

      {/* Right form half */}
      <div style={{ padding: 56, display: 'flex', flexDirection: 'column', justifyContent: 'center', overflowY: 'auto' }}>
        <div style={{ width: '100%', maxWidth: 460, marginInline: 'auto' }}>
          {children}
          {footer && <div style={{ marginTop: 28, fontSize: 13, color: '#5a5a54' }}>{footer}</div>}
        </div>
      </div>

      <style>{`
        @media (max-width: 820px) {
          .dc-auth-aside { display: none !important; }
          div:has(> .dc-auth-aside) { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

// A plain text link styled consistently.
function AuthLink({ children, onClick }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', padding: 0,
      fontFamily: 'inherit', color: '#1a1a18', fontSize: 'inherit',
      textDecoration: 'underline', textUnderlineOffset: 3,
    }}>{children}</button>
  );
}

// Small inline error / banner.
function FormBanner({ kind = 'error', children }) {
  const styles = {
    error: { bg: 'rgba(168,51,26,0.07)', border: 'rgba(168,51,26,0.25)', fg: '#a8331a' },
    info:  { bg: '#F2EFE7', border: 'rgba(20,20,18,0.08)', fg: '#3a3a36' },
  }[kind];
  return (
    <div style={{
      padding: '11px 14px', borderRadius: 10, marginBottom: 16,
      background: styles.bg, border: `1px solid ${styles.border}`,
      fontSize: 12.5, color: styles.fg, lineHeight: 1.45,
    }}>{children}</div>
  );
}

// ─── Sign up ────────────────────────────────────────────────────────────────
const STYLE_TAGS = ['streetwear', 'minimal', 'vintage', 'sport', 'summer', 'formal', 'workwear', 'tonal', 'archive', 'monochrome'];

function SignupScreen({ go }) {
  const [fullName, setFullName]   = useStateAU('');
  const [creatorName, setCreator] = useStateAU('');
  const [email, setEmail]         = useStateAU('');
  const [pwd, setPwd]             = useStateAU('');
  const [instagram, setInstagram] = useStateAU('');
  const [tiktok, setTiktok]       = useStateAU('');
  const [website, setWebsite]     = useStateAU('');
  const [tags, setTags]           = useStateAU([]);
  const [error, setError]         = useStateAU(null);
  const [busy, setBusy]           = useStateAU(false);

  const handleFromCreator = (creatorName || fullName || '').toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 20);
  const cleanHandle = (v) => v.trim().replace(/^@+/, '');

  const submit = async () => {
    if (busy) return;
    if (!fullName.trim() || !creatorName.trim() || !email.trim() || !pwd.trim()) {
      setError('Please fill in your name, creator name, email and password.');
      return;
    }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
      setError('That email doesn’t look right.');
      return;
    }
    // Supabase enforces 6 characters by default; check here for a nicer message.
    if (pwd.length < 6) {
      setError('Use at least 6 characters for your password.');
      return;
    }
    setError(null);
    setBusy(true);
    // Remembered so the confirm-email screen can name the address (there is no
    // session to read it from until the account is confirmed).
    window.__mbPendingEmail = email.trim();
    const res = await MBAuth.signUp({
      email,
      password: pwd,
      profile: {
        fullName: fullName.trim(),
        creatorName: creatorName.trim(),
        handle: (cleanHandle(instagram) || handleFromCreator),
        // These land on the public profile row: mb_handle_new_user() copies
        // them across as the account is created, so they survive the wait for
        // an email confirmation, when there is no session to save them from.
        instagram: instagram.trim(),
        tiktok: tiktok.trim(),
        website: website.trim(),
        tags,
      },
    });
    setBusy(false);
    if (res.error) { setError(res.error); return; }
    // No session back means the project has email confirmation switched on.
    go({ name: res.needsConfirmation ? 'verify' : 'myoutfits' });
  };

  return (
    <AuthLayout footer={<>Already have an account? <AuthLink onClick={() => go({ name: 'login' })}>Log in</AuthLink></>}>
      <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>Apply as creator</div>
      <h2 style={{ margin: '8px 0 0', fontSize: 38, fontWeight: 400, letterSpacing: '-0.025em' }}>Join modaBoard Studio</h2>
      <p style={{ marginTop: 10, color: '#5a5a54', fontSize: 14, lineHeight: 1.55 }}>
        Create outfits, tag products, track clicks, and earn affiliate revenue from your wardrobe.
      </p>

      <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {error && <FormBanner>{error}</FormBanner>}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Full name" value={fullName} onChange={setFullName} placeholder="Aimé Oh"/>
          <Field label="Creator / display name" value={creatorName} onChange={setCreator} placeholder="aimeoh"/>
        </div>
        <Field label="Email" value={email} onChange={setEmail} type="email" placeholder="you@studio.com"/>
        <Field label="Password" value={pwd} onChange={setPwd} type="password" placeholder="At least 6 characters"/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Instagram" value={instagram} onChange={setInstagram} prefix="@" placeholder="optional"/>
          <Field label="TikTok" value={tiktok} onChange={setTiktok} prefix="@" placeholder="optional"/>
        </div>
        <Field label="Website / portfolio" value={website} onChange={setWebsite} placeholder="optional"/>
        <div>
          <label style={{ display: 'block', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8a8580', marginBottom: 10 }}>
            Style categories <span style={{ textTransform: 'none', letterSpacing: 0, color: '#a8a39d' }}>· optional</span>
          </label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {STYLE_TAGS.map(tag => {
              const on = tags.includes(tag);
              return (
                <button key={tag} onClick={() => setTags(prev => on ? prev.filter(x => x !== tag) : [...prev, tag])} style={{
                  appearance: 'none', cursor: 'pointer', padding: '8px 13px', borderRadius: 999,
                  fontSize: 11.5, fontFamily: 'inherit',
                  border: '1px solid', borderColor: on ? '#1a1a18' : 'rgba(20,20,18,0.14)',
                  background: on ? '#1a1a18' : 'transparent', color: on ? '#FAFAF7' : '#1a1a18',
                }}>{tag}</button>
              );
            })}
          </div>
        </div>
        <button onClick={submit} disabled={busy} style={{ ...btnPrimary, marginTop: 8, opacity: busy ? 0.6 : 1 }}>
          {busy ? 'Creating account…' : 'Create studio account'}
        </button>
      </div>
    </AuthLayout>
  );
}

// ─── Log in ─────────────────────────────────────────────────────────────────
function LoginScreen({ go }) {
  const [email, setEmail] = useStateAU('');
  const [pwd, setPwd]     = useStateAU('');
  const [error, setError] = useStateAU(null);
  const [busy, setBusy]   = useStateAU(false);

  const login = async () => {
    if (busy) return;
    if (!email.trim() || !pwd.trim()) { setError('Enter your email and password.'); return; }
    setError(null);
    setBusy(true);
    const res = await MBAuth.signIn({ email, password: pwd });
    setBusy(false);
    if (res.error) { setError(res.error); return; }
    go({ name: 'myoutfits' });
  };

  return (
    <AuthLayout footer={<>Don’t have an account? <AuthLink onClick={() => go({ name: 'signup' })}>Apply as creator</AuthLink></>}>
      <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>Creator Studio</div>
      <h2 style={{ margin: '8px 0 0', fontSize: 38, fontWeight: 400, letterSpacing: '-0.025em' }}>Log in to your Studio</h2>
      <p style={{ marginTop: 10, color: '#5a5a54', fontSize: 14 }}>Welcome back. Pick up where your wardrobe left off.</p>

      <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {error && <FormBanner>{error}</FormBanner>}
        <Field label="Email" value={email} onChange={setEmail} type="email" placeholder="you@studio.com"/>
        <Field label="Password" value={pwd} onChange={setPwd} type="password"/>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: -4 }}>
          <span style={{ fontSize: 12.5, color: '#5a5a54' }}><AuthLink onClick={() => go({ name: 'forgot' })}>Forgot password?</AuthLink></span>
        </div>
        <button onClick={login} disabled={busy} style={{ ...btnPrimary, marginTop: 8, opacity: busy ? 0.6 : 1 }}>
          {busy ? 'Logging in…' : 'Log in'}
        </button>
      </div>
    </AuthLayout>
  );
}

// ─── Forgot password ────────────────────────────────────────────────────────
function ForgotPasswordScreen({ go }) {
  const [email, setEmail] = useStateAU('');
  const [sent, setSent]   = useStateAU(false);
  const [error, setError] = useStateAU(null);
  const [busy, setBusy]   = useStateAU(false);

  const sendReset = async () => {
    if (busy || !email.trim()) return;
    setError(null);
    setBusy(true);
    const res = await MBAuth.resetPassword(email);
    setBusy(false);
    // Show the same confirmation either way so this can't be used to probe
    // which addresses have accounts.
    if (res.error) { setError(res.error); return; }
    setSent(true);
  };

  return (
    <AuthLayout footer={<>Remembered it? <AuthLink onClick={() => go({ name: 'login' })}>Back to log in</AuthLink></>}>
      <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>Account recovery</div>
      <h2 style={{ margin: '8px 0 0', fontSize: 38, fontWeight: 400, letterSpacing: '-0.025em' }}>Reset your password</h2>
      {sent ? (
        <>
          <FormBanner kind="info">
            If an account exists for <strong style={{ fontWeight: 500 }}>{email}</strong>, we’ve sent a reset link. Check your inbox (and spam).
          </FormBanner>
          <button onClick={() => go({ name: 'login' })} style={btnPrimary}>Back to log in</button>
        </>
      ) : (
        <>
          <p style={{ marginTop: 10, color: '#5a5a54', fontSize: 14, lineHeight: 1.55 }}>
            Enter the email tied to your Studio and we’ll send you a link to set a new password.
          </p>
          <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 14 }}>
            {error && <FormBanner>{error}</FormBanner>}
            <Field label="Email" value={email} onChange={setEmail} type="email" placeholder="you@studio.com"/>
            <button onClick={sendReset} disabled={busy} style={{ ...btnPrimary, marginTop: 6, opacity: busy ? 0.6 : 1 }}>
              {busy ? 'Sending…' : 'Send reset link'}
            </button>
          </div>
        </>
      )}
    </AuthLayout>
  );
}

// ─── Account-state: email verification ──────────────────────────────────────
function VerifyEmailScreen({ go }) {
  const session = useSession();
  // After sign-up there is no session yet, so fall back to the address the
  // sign-up form last used.
  const [email] = useStateAU(() => session?.email || window.__mbPendingEmail || '');
  const [note, setNote] = useStateAU(null);

  const resend = async () => {
    if (!email) { setNote('Enter your email on the sign-up form again to resend.'); return; }
    const res = await MBAuth.resendConfirmation(email);
    setNote(res.error ? res.error : 'Confirmation email sent — check your inbox.');
  };

  return (
    <AuthStateLayout
      kicker="One more step · Confirm email"
      title="Confirm your email"
      icon="mail"
      body={<>We’ve sent a confirmation link to <strong style={{ fontWeight: 500 }}>{email || 'your email'}</strong>. Click it to activate your account, then log in.</>}
      primary={{ label: 'I’ve confirmed — log in', onClick: () => go({ name: 'login' }) }}
      secondary={{ label: 'Resend email', onClick: resend }}
      tertiary={{ label: 'Use a different email', onClick: () => go({ name: 'signup' }) }}
      note={note ? <div style={{ marginTop: 18 }}><FormBanner kind="info">{note}</FormBanner></div> : null}
    />
  );
}

// ─── Account-state: pending approval ────────────────────────────────────────
function PendingApprovalScreen({ go }) {
  const session = useSession();
  return (
    <AuthStateLayout
      kicker="Step 2 of 2 · Under review"
      title="Your Studio is under review"
      icon="clock"
      body={<>Thanks for applying to modaBoard Studio{session?.creatorName ? `, ${session.creatorName.split(' ')[0]}` : ''}. We’ll review your profile and email you once your account is approved — usually within two working days.</>}
      primary={{ label: 'Back to home', onClick: () => go({ name: 'home' }) }}
      note={
        <div style={{ marginTop: 22, padding: 14, borderRadius: 12, background: '#F2EFE7', fontSize: 12, color: '#5a5550', lineHeight: 1.5 }}>
          <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#8a8580', marginBottom: 8 }}>Demo controls</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => { DripcheckAuth.patch({ status: 'approved' }); go({ name: 'studio' }); }} style={{ ...btnPrimary, padding: '9px 14px', fontSize: 10.5 }}>Approve account →</button>
            <button onClick={() => { DripcheckAuth.patch({ status: 'rejected' }); go({ name: 'rejected' }); }} style={{ ...btnGhost, padding: '9px 14px', fontSize: 10.5 }}>Simulate rejection</button>
          </div>
        </div>
      }
    />
  );
}

// ─── Account-state: rejected ────────────────────────────────────────────────
function RejectedScreen({ go }) {
  return (
    <AuthStateLayout
      kicker="Application closed"
      title="Not approved — for now"
      icon="x"
      body="We’re not able to approve your Studio account at this time. This is usually about audience fit or incomplete profiles — you’re welcome to reapply in 30 days with more detail."
      primary={{ label: 'Back to home', onClick: () => go({ name: 'home' }) }}
      secondary={{ label: 'Reapply', onClick: () => { DripcheckAuth.clear(); go({ name: 'signup' }); } }}
    />
  );
}

// Shared centered layout for account-state screens.
function AuthStateLayout({ kicker, title, body, icon, primary, secondary, tertiary, note }) {
  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: '#FAFAF7' }}>
      <div style={{ width: '100%', maxWidth: 460, textAlign: 'center' }}>
        <button onClick={() => window.__dripcheckGo?.({ name: 'home' })} style={{ appearance: 'none', border: 'none', background: 'transparent', padding: 0, cursor: 'pointer', marginBottom: 36, display: 'inline-block' }}>
          <Logo size={20}/>
        </button>
        <div style={{
          width: 56, height: 56, borderRadius: '50%', marginInline: 'auto',
          background: '#F2EFE7', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <StateIcon name={icon}/>
        </div>
        <div style={{ marginTop: 22, fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>{kicker}</div>
        <h1 style={{ margin: '10px 0 0', fontSize: 34, fontWeight: 400, letterSpacing: '-0.025em' }}>{title}</h1>
        <p style={{ marginTop: 14, fontSize: 15, color: '#3a3a36', lineHeight: 1.6, textWrap: 'pretty' }}>{body}</p>
        <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {primary && <button onClick={primary.onClick} style={btnPrimary}>{primary.label}</button>}
          {secondary && <button onClick={secondary.onClick} style={btnGhost}>{secondary.label}</button>}
          {tertiary && <span style={{ fontSize: 12.5, color: '#5a5a54' }}><AuthLink onClick={tertiary.onClick}>{tertiary.label}</AuthLink></span>}
        </div>
        {note}
      </div>
    </div>
  );
}

function StateIcon({ name }) {
  const s = { width: 24, height: 24, fill: 'none', stroke: '#1a1a18', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const map = {
    mail:  <svg {...s} viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>,
    clock: <svg {...s} viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
    x:     <svg {...s} viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M15 9l-6 6M9 9l6 6"/></svg>,
  };
  return map[name] || null;
}

// Route helper — kept for existing call sites. With Supabase accounts there is
// no approval queue: a live session means full access.
function routeByStatus(_status, go) {
  return go({ name: MBAuth.isSignedIn() ? 'studio' : 'login' });
}
window.routeByStatus = routeByStatus;

Object.assign(window, {
  useSession, AuthLayout, AuthLink, FormBanner,
  SignupScreen, LoginScreen, ForgotPasswordScreen,
  VerifyEmailScreen, PendingApprovalScreen, RejectedScreen,
  AuthStateLayout, routeByStatus,
});
