/* Rinse n Repeat — admin auth gate + onboarding.
   Wraps window.RNRAdmin. Handles: not-signed-in -> login; signed-in but no
   business -> onboarding; otherwise -> dashboard. Works in both store modes
   (local = passcode demo, supabase = real email/password auth).
   Exposed as window.RNRAdminApp. */
(function () {
  const { Button, Icon, Input } = window.RinseNRepeatDesignSystem_9f80bd;
  const isLocal = window.RNRStore.mode === 'local';

  function Shell({ children }) {
    return (
      <div style={{ minHeight:'100vh', background:'var(--black-950)', display:'flex', alignItems:'center', justifyContent:'center', padding:24, fontFamily:'var(--font-body)' }}>
        <div style={{ width:'100%', maxWidth:400 }}>
          <img src="assets/logo-dark.png" alt="Rinse n Repeat" style={{ height:56, display:'block', margin:'0 auto 26px' }} />
          <div style={{ background:'#fff', borderRadius:'var(--radius-2xl)', boxShadow:'var(--shadow-lg)', padding:32 }}>{children}</div>
          <p style={{ textAlign:'center', color:'rgba(255,255,255,.4)', fontSize:12.5, marginTop:20 }}>Owner access · Rinse n Repeat Appointment Manager</p>
        </div>
      </div>
    );
  }

  function Login({ onDone }) {
    const [mode, setMode] = React.useState('signin'); // signin | signup
    const [email, setEmail] = React.useState('');
    const [password, setPassword] = React.useState('');
    const [passcode, setPasscode] = React.useState('');
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const [note, setNote] = React.useState(null);

    async function submit() {
      setBusy(true); setErr(null); setNote(null);
      try {
        if (isLocal) {
          await window.RNRStore.auth.signIn('', passcode);
          onDone();
        } else if (mode === 'signup') {
          await window.RNRStore.auth.signUp(email, password);
          const user = await window.RNRStore.auth.getUser();
          if (user) onDone(); else setNote('Check your email to confirm your account, then sign in.');
        } else {
          await window.RNRStore.auth.signIn(email, password);
          onDone();
        }
      } catch (e) { setErr(e.message || 'Sign-in failed.'); } finally { setBusy(false); }
    }

    return (
      <Shell>
        <h1 style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:24, margin:'0 0 6px', color:'var(--black-900)' }}>{isLocal ? 'Owner login' : (mode==='signup' ? 'Create your account' : 'Welcome back')}</h1>
        <p style={{ color:'var(--gray-600)', fontSize:14, margin:'0 0 22px' }}>{isLocal ? 'Enter your passcode to manage appointments.' : 'Sign in to manage your appointments.'}</p>
        <form onSubmit={(e)=>{e.preventDefault();submit();}} style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {isLocal ? (
            <Input label="Passcode" type="password" value={passcode} onChange={(e)=>setPasscode(e.target.value)} placeholder="••••••" icon={<Icon name="lock" size={18} />} />
          ) : (
            <>
              <Input label="Email" type="email" value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="you@email.com" icon={<Icon name="mail" size={18} />} />
              <Input label="Password" type="password" value={password} onChange={(e)=>setPassword(e.target.value)} placeholder="••••••••" icon={<Icon name="lock" size={18} />} />
            </>
          )}
          {err ? <div style={{ color:'var(--danger-500)', fontSize:13, background:'var(--danger-050)', padding:'9px 12px', borderRadius:'var(--radius-sm)' }}>{err}</div> : null}
          {note ? <div style={{ color:'var(--success-500)', fontSize:13, background:'var(--success-050)', padding:'9px 12px', borderRadius:'var(--radius-sm)' }}>{note}</div> : null}
          <Button type="submit" variant="primary" size="lg" fullWidth disabled={busy}>{busy ? 'Please wait…' : (isLocal ? 'Unlock' : (mode==='signup' ? 'Create account' : 'Sign in'))}</Button>
        </form>
        {!isLocal ? (
          <p style={{ textAlign:'center', fontSize:13.5, color:'var(--gray-600)', margin:'18px 0 0' }}>
            {mode==='signup' ? 'Already have an account? ' : 'New here? '}
            <a onClick={()=>{setMode(mode==='signup'?'signin':'signup');setErr(null);setNote(null);}} style={{ color:'var(--orange-600)', fontWeight:600, cursor:'pointer' }}>{mode==='signup' ? 'Sign in' : 'Create an account'}</a>
          </p>
        ) : null}
      </Shell>
    );
  }

  function Onboarding({ onDone }) {
    const [f, setF] = React.useState({ name:'', slug:'', phone:'', email:'', area:'' });
    const set = (k) => (e) => setF((p)=>({ ...p, [k]: e.target.value }));
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const slugify = (s) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
    async function submit() {
      setBusy(true); setErr(null);
      try {
        await window.RNRStore.createTenant({ name: f.name, slug: f.slug || slugify(f.name), phone: f.phone, email: f.email, area: f.area });
        onDone();
      } catch (e) { setErr(e.message === 'slug_taken' ? 'That web address is taken — try another.' : (e.message || 'Could not create business.')); } finally { setBusy(false); }
    }
    return (
      <Shell>
        <h1 style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:24, margin:'0 0 6px', color:'var(--black-900)' }}>Set up your business</h1>
        <p style={{ color:'var(--gray-600)', fontSize:14, margin:'0 0 22px' }}>One quick step — then your calendar is ready.</p>
        <form onSubmit={(e)=>{e.preventDefault();submit();}} style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Input label="Business name" value={f.name} onChange={(e)=>setF((p)=>({...p,name:e.target.value,slug:p.slug||slugify(e.target.value)}))} placeholder="e.g. Rinse n Repeat" />
          <Input label="Booking web address" value={f.slug} onChange={set('slug')} hint="Used in your booking link (letters, numbers, dashes)" placeholder="rinse-n-repeat" />
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(min(160px,100%),1fr))', gap:12 }}>
            <Input label="Phone" value={f.phone} onChange={set('phone')} placeholder="(555) 000-0000" />
            <Input label="Service area" value={f.area} onChange={set('area')} placeholder="Plainfield, IL" />
          </div>
          <Input label="Contact email" type="email" value={f.email} onChange={set('email')} placeholder="you@email.com" />
          {err ? <div style={{ color:'var(--danger-500)', fontSize:13, background:'var(--danger-050)', padding:'9px 12px', borderRadius:'var(--radius-sm)' }}>{err}</div> : null}
          <Button type="submit" variant="primary" size="lg" fullWidth disabled={busy}>{busy ? 'Creating…' : 'Create business'}</Button>
        </form>
      </Shell>
    );
  }

  function AdminApp() {
    const [phase, setPhase] = React.useState('loading'); // loading | login | onboarding | ready
    const [tenant, setTenant] = React.useState(null);

    const resolve = React.useCallback(async () => {
      const user = await window.RNRStore.auth.getUser();
      if (!user) { setPhase('login'); return; }
      const t = await window.RNRStore.getMyTenant();
      if (!t) { setPhase('onboarding'); return; }
      setTenant(t); setPhase('ready');
    }, []);

    React.useEffect(() => { resolve().catch(()=>setPhase('login')); }, [resolve]);

    const lock = async () => { try { await window.RNRStore.auth.signOut(); } catch (_) {} setTenant(null); setPhase('login'); };

    if (phase === 'loading') return <div style={{ minHeight:'100vh', background:'var(--black-950)', color:'rgba(255,255,255,.6)', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'var(--font-body)' }}>Loading…</div>;
    if (phase === 'login') return <Login onDone={resolve} />;
    if (phase === 'onboarding') return <Onboarding onDone={resolve} />;
    const Dashboard = window.RNRAdmin;
    return <Dashboard tenant={tenant} onLock={lock} />;
  }

  window.RNRAdminApp = AdminApp;
})();
