/* GarageWiz — Login + Dashboard */
(function () {
  const e = React.createElement;
  const { useState } = React;
  const Icon = window.Icon, Btn = window.Btn, Wordmark = window.Wordmark, Mascot = window.Mascot, Input = window.Input, Field = window.Field;

  /* ===================== LOGIN ===================== */
  function LoginScreen() {
    const app = window.useApp();
    const [email, setEmail] = useState('');
    const [pw, setPw] = useState('');
    const [showPw, setShowPw] = useState(false);
    const [err, setErr] = useState('');
    const [busy, setBusy] = useState(false);
    const [mode, setMode] = useState('signin');   // 'signin' | 'signup'
    const [name, setName] = useState('');
    const backend = !!(window.GW.db && window.GW.db.configured);

    async function signUp() {
      if (!name.trim() || !email.trim() || !pw) { setErr('Enter your name, email and a password.'); return; }
      if (pw.length < 6) { setErr('Password must be at least 6 characters.'); return; }
      setBusy(true); setErr('');
      try {
        const res = await GW.db.signUp(email.trim(), pw, name.trim());
        if (res && res.session) { /* auto-confirmed → onAuth logs us in */ }
        else { setMode('signin'); app.toast('Account created — check your email to confirm, then sign in.'); }
      } catch (e) { setErr((e && e.message) || 'Sign up failed.'); }
      setBusy(false);
    }

    async function submit(asRole) {
      if (asRole) { app.login(asRole === 'admin' ? GW.users[0] : GW.users[1]); return; }
      if (backend) {
        if (!email.trim() || !pw) { setErr('Enter your email and password.'); return; }
        setBusy(true); setErr('');
        try {
          await GW.db.signIn(email.trim(), pw);
          const prof = await GW.db.profile();
          if (prof) { GW.db.logEvent('login', {}); app.login({ id: prof.id, name: prof.name, email: prof.email, role: prof.role, active: prof.active }); }
          else { setErr('Signed in, but no profile found — contact an admin.'); }
        } catch (e) { setErr((e && e.message) ? e.message : 'Sign in failed. Check your email and password.'); }
        setBusy(false);
        return;
      }
      // demo / local fallback (no backend configured)
      const found = GW.users.find(u => u.email.toLowerCase() === email.trim().toLowerCase());
      if (!found) { setErr('No matching account. Try a demo login below.'); return; }
      if (!pw) { setErr('Enter your password.'); return; }
      app.login(found);
    }

    return e('div', { style: { minHeight: '100vh', display: 'flex', background: 'var(--navy)' } },
      // Brand panel
      e('div', { className: 'login-brand', style: {
        flex: '1 1 46%', background: 'linear-gradient(160deg, var(--teal) 0%, var(--teal-800) 60%, var(--navy) 100%)',
        position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '46px 52px',
      } },
        e('div', { style: { position: 'absolute', inset: 0, opacity: .5, background: 'radial-gradient(700px 500px at 80% 10%, rgba(0,177,237,.35), transparent 60%)' } }),
        e('div', { style: { position: 'relative' } }, e(Wordmark, { height: 56 })),
        e('div', { style: { position: 'relative' } },
          e('div', { className: 'display', style: { color: '#fff', fontSize: 38, lineHeight: 1.08, fontWeight: 600, maxWidth: 440 } }, "Let's find the perfect door for your home."),
          e('div', { style: { color: 'rgba(255,255,255,.8)', fontSize: 16.5, marginTop: 14, maxWidth: 400 } }, 'Browse your options, see exactly what’s included, and get a clear price on the spot — no waiting, no surprises, no pressure.'),
        ),
        e('div', { style: { position: 'relative', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16 } },
          e('div', { style: { color: 'rgba(255,255,255,.55)', fontSize: 13, paddingBottom: 8 } }, 'Internal tool · Confidential'),
          e(Mascot, { size: 150, style: { filter: 'drop-shadow(0 16px 26px rgba(0,0,0,.35))', marginRight: -8, marginBottom: -10 } }),
        ),
      ),
      // Form
      e('div', { style: { flex: '1 1 54%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px 24px', background: 'var(--paper)' } },
        e('div', { style: { width: '100%', maxWidth: 400, animation: 'gw-rise .5s ease both' } },
          e('div', { className: 'login-brand-sm', style: { display: 'none', marginBottom: 26, textAlign: 'center' } }, e('img', { src: 'assets/wordmark.jpg', alt: 'GarageWiz', style: { height: 78, borderRadius: 12 } })),
          e('h1', { className: 'display', style: { fontSize: 30, fontWeight: 600, margin: '0 0 6px' } }, mode === 'signup' ? 'Create your account' : 'Sign in'),
          e('p', { className: 'muted', style: { marginTop: 0, marginBottom: 26, fontSize: 15 } }, mode === 'signup' ? 'Sign up to start pricing. An admin sets your access.' : 'Use your GarageWiz account to continue.'),

          e('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
            mode === 'signup' ? e(Field, { label: 'Full name' }, e(Input, { placeholder: 'Jane Smith', value: name, onChange: ev => { setName(ev.target.value); setErr(''); } })) : null,
            e(Field, { label: 'Email' }, e(Input, { type: 'email', placeholder: 'you@garagewiz.com', value: email, onChange: ev => { setEmail(ev.target.value); setErr(''); }, autoFocus: true })),
            e(Field, { label: 'Password' },
              e('div', { style: { position: 'relative' } },
                e(Input, { type: showPw ? 'text' : 'password', placeholder: '••••••••', value: pw, onChange: ev => { setPw(ev.target.value); setErr(''); }, style: { paddingRight: 46 }, onKeyDown: ev => ev.key === 'Enter' && (mode === 'signup' ? signUp() : submit()) }),
                e('button', { onClick: () => setShowPw(s => !s), type: 'button', style: { position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', color: 'var(--ink-3)', padding: 6, cursor: 'pointer' } }, e(Icon, { name: showPw ? 'eyeOff' : 'eye', size: 19 })),
              ),
            ),
            err ? e('div', { style: { color: 'var(--danger)', fontSize: 13.5, fontWeight: 600 } }, err) : null,
            mode === 'signup'
              ? e(Btn, { variant: 'primary', size: 'lg', block: true, disabled: busy, onClick: () => signUp(), iconRight: busy ? null : 'arrowR' }, busy ? 'Creating…' : 'Create account')
              : e(Btn, { variant: 'primary', size: 'lg', block: true, disabled: busy, onClick: () => submit(), iconRight: busy ? null : 'arrowR' }, busy ? 'Signing in…' : 'Sign in'),
            // self-registration is intentionally disabled — accounts are created by an admin
          ),

          // demo login only when there's no real backend configured
          !backend ? e('div', { style: { display: 'flex', alignItems: 'center', gap: 12, margin: '26px 0 18px', color: 'var(--ink-3)', fontSize: 12.5, fontWeight: 700, letterSpacing: '.08em' } },
            e('div', { style: { flex: 1, height: 1, background: 'var(--line)' } }), 'QUICK DEMO LOGIN', e('div', { style: { flex: 1, height: 1, background: 'var(--line)' } }),
          ) : null,
          !backend ? e('div', { style: { display: 'flex', gap: 12 } },
            e(Btn, { variant: 'ghost', block: true, onClick: () => submit('admin'), icon: 'settings' }, 'As Admin'),
            e(Btn, { variant: 'ghost', block: true, onClick: () => submit('rep'), icon: 'users' }, 'As Rep'),
          ) : null,
        ),
      ),
    );
  }
  window.LoginScreen = LoginScreen;

  /* ===================== DASHBOARD ===================== */
  function ModuleCard({ icon, title, sub, route, accent }) {
    const app = window.useApp();
    const [hover, setHover] = useState(false);
    return e('button', {
      onClick: () => app.go(route),
      onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
      style: {
        textAlign: 'left', border: 'none', cursor: 'pointer', background: '#fff', borderRadius: 'var(--r-xl)',
        padding: '30px', boxShadow: hover ? 'var(--sh-3)' : 'var(--sh-2)', transform: hover ? 'translateY(-4px)' : 'none',
        transition: 'transform .18s, box-shadow .18s', position: 'relative', overflow: 'hidden',
        display: 'flex', flexDirection: 'column', gap: 16, minHeight: 200,
      },
    },
      e('div', { style: { position: 'absolute', right: -30, top: -30, width: 140, height: 140, borderRadius: 999, background: accent, opacity: .1 } }),
      e('div', { style: { width: 64, height: 64, borderRadius: 18, background: accent, color: '#fff', display: 'grid', placeItems: 'center', boxShadow: '0 8px 18px ' + accent + '55' } }, e(Icon, { name: icon, size: 32 })),
      e('div', { className: 'grow' },
        e('div', { className: 'display', style: { fontSize: 26, fontWeight: 600 } }, title),
        e('div', { className: 'muted', style: { fontSize: 14.5, marginTop: 4, maxWidth: 240 } }, sub),
      ),
      e('div', { style: { display: 'flex', alignItems: 'center', gap: 8, color: accent, fontFamily: 'var(--display)', fontWeight: 600, fontSize: 15 } }, 'Open', e(Icon, { name: 'arrowR', size: 18, style: { transform: hover ? 'translateX(4px)' : 'none', transition: 'transform .18s' } })),
    );
  }

  function Dashboard() {
    const app = window.useApp();
    const isAdmin = app.user && app.user.role === 'admin';
    const me = GW.activity.find(a => a.user === (app.user && app.user.name)) || GW.activity[0];

    const statusPill = (s) => {
      const map = { won: ['badge-good', 'Won'], sent: ['badge-prem', 'Sent'], open: ['badge-start', 'Open'] };
      return e('span', { className: 'badge ' + map[s][0] }, map[s][1]);
    };

    return e('div', { style: { maxWidth: 1480, margin: '0 auto', padding: '34px 28px 80px' } },
      // greeting
      e('div', { className: 'dash-hero', style: { display: 'flex', alignItems: 'center', gap: 22, marginBottom: 30 } },
        e('div', { className: 'grow' },
          e('div', { className: 'eyebrow' }, 'Welcome back'),
          e('h1', { className: 'display', style: { fontSize: 36, fontWeight: 600, margin: '4px 0 0' } }, 'Hi, ' + (app.user ? app.user.name.split(' ')[0] : '') + ' 👋'),
          e('p', { className: 'muted', style: { fontSize: 16, margin: '6px 0 0' } }, 'Pick a module to start a quote. Every price updates live as you build it.'),
        ),
        e(Mascot, { size: 120, className: 'dash-mascot' }),
      ),

      // modules
      e('div', { className: 'module-grid', style: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 22, marginBottom: 36 } },
        e(ModuleCard, { icon: 'door', title: 'Doors', sub: 'Configure a door with optional opener & add-ons', route: '#/doors', accent: 'var(--teal)' }),
        e(ModuleCard, { icon: 'opener', title: 'Openers', sub: 'Full opener catalog for standalone sales', route: '#/openers', accent: 'var(--blue)' }),
        e(ModuleCard, { icon: 'parts', title: 'Parts', sub: 'Springs, rollers, cables & more', route: '#/parts', accent: '#1FA463' }),
      ),

      e('div', { className: 'dash-cols', style: { display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 22 } },
        // recent quotes
        e('div', { className: 'card', style: { padding: 24 } },
          e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 } },
            e('div', { className: 'display', style: { fontSize: 20, fontWeight: 600 } }, 'Recent quotes'),
            e('div', { style: { display: 'flex', gap: 8 } },
              (window.GW.db && window.GW.db.configured) ? e(Btn, { variant: 'ghost', size: 'sm', icon: 'briefcase', onClick: () => app.go('#/estimates') }, 'My estimates') : null,
              e(Btn, { variant: 'ghost', size: 'sm', icon: 'plus', onClick: () => { app.resetConfig(); app.go('#/doors'); } }, 'New quote'),
            ),
          ),
          e('div', { style: { display: 'flex', flexDirection: 'column' } },
            GW.recentQuotes.map((q, i) => e('div', { key: q.id, style: { display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderTop: i ? '1px solid var(--line)' : 'none' } },
              e('div', { style: { width: 44, height: 44, borderRadius: 12, background: 'var(--field)', display: 'grid', placeItems: 'center', color: 'var(--teal)', flexShrink: 0 } }, e(Icon, { name: 'door', size: 22 })),
              e('div', { className: 'grow', style: { minWidth: 0 } },
                e('div', { style: { fontWeight: 700, fontSize: 15 } }, q.customer),
                e('div', { className: 'muted', style: { fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }, q.spec + ' · ' + q.when),
              ),
              e('div', { style: { textAlign: 'right', flexShrink: 0 } },
                e('div', { className: 'display num', style: { fontWeight: 600, fontSize: 17 } }, GW.fmt(q.price)),
                e('div', { style: { marginTop: 3 } }, statusPill(q.status)),
              ),
            )),
          ),
        ),
        // your stats
        e('div', { className: 'card', style: { padding: 24, background: 'linear-gradient(165deg, var(--navy) 0%, var(--navy-deep) 100%)', color: '#fff' } },
          e('div', { className: 'eyebrow', style: { color: 'var(--yellow)' } }, isAdmin ? 'Team this month' : 'Your month'),
          e('div', { className: 'display', style: { fontSize: 20, fontWeight: 600, marginTop: 4, marginBottom: 18 } }, isAdmin ? 'Shop performance' : 'Keep it rolling'),
          e('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 } },
            [['Quotes', me.quotes], ['Quoted value', GW.fmt(isAdmin ? GW.activity.reduce((s, a) => s + a.value, 0) : me.value)], ['Avg job', GW.fmt(me.avg)], ['Top add-on', me.topAddon]].map((s, i) =>
              e('div', { key: i, style: { background: 'rgba(255,255,255,.07)', borderRadius: 14, padding: '14px 16px' } },
                e('div', { style: { fontSize: 12.5, color: 'rgba(255,255,255,.65)', fontWeight: 700, letterSpacing: '.04em' } }, s[0]),
                e('div', { className: 'display num', style: { fontSize: 24, fontWeight: 600, marginTop: 4, color: 'var(--yellow)' } }, s[1]),
              )),
          ),
          isAdmin ? e(Btn, { variant: 'dark', block: true, icon: 'activity', onClick: () => app.go('#/admin/activity'), style: { marginTop: 18 } }, 'View full activity') : null,
        ),
      ),
    );
  }
  window.Dashboard = Dashboard;

  /* ===================== HUB (tool launcher) ===================== */
  function ToolCard({ tool, state }) {
    const app = window.useApp();
    const [hover, setHover] = useState(false);
    const clickable = state === 'active';
    const muted = state !== 'active';
    const badge = state === 'active' ? ['badge-good', 'Available']
      : state === 'coming_soon' ? ['badge-order', 'Coming Soon']
      : ['badge-start', 'Locked'];

    return e('button', {
      onClick: () => clickable && app.go(tool.route),
      onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
      disabled: !clickable,
      style: {
        textAlign: 'left', border: 'none', cursor: clickable ? 'pointer' : 'default', background: '#fff',
        borderRadius: 'var(--r-xl)', padding: '26px', boxShadow: hover && clickable ? 'var(--sh-3)' : 'var(--sh-2)',
        transform: hover && clickable ? 'translateY(-4px)' : 'none', transition: 'transform .18s, box-shadow .18s',
        position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', gap: 14, minHeight: 196,
        opacity: muted ? .68 : 1,
      },
    },
      e('div', { style: { position: 'absolute', right: -30, top: -30, width: 130, height: 130, borderRadius: 999, background: tool.accent, opacity: .1 } }),
      e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
        e('div', { style: { width: 60, height: 60, borderRadius: 17, background: tool.accent, color: '#fff', display: 'grid', placeItems: 'center', boxShadow: '0 8px 18px ' + tool.accent + '55', filter: muted ? 'grayscale(.5)' : 'none' } }, e(Icon, { name: tool.icon, size: 30 })),
        state === 'locked' ? e('span', { style: { color: 'var(--ink-3)' } }, e(Icon, { name: 'lock', size: 18 })) : null,
      ),
      e('div', { className: 'grow' },
        e('div', { className: 'display', style: { fontSize: 22, fontWeight: 600 } }, tool.name),
        e('div', { className: 'muted', style: { fontSize: 14, marginTop: 4, lineHeight: 1.4 } }, tool.desc),
      ),
      e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
        e('span', { className: 'badge ' + badge[0] }, badge[1]),
        clickable ? e('span', { style: { display: 'flex', alignItems: 'center', gap: 6, color: tool.accent, fontFamily: 'var(--display)', fontWeight: 600, fontSize: 14.5 } }, 'Open', e(Icon, { name: 'arrowR', size: 17, style: { transform: hover ? 'translateX(4px)' : 'none', transition: 'transform .18s' } })) : null,
      ),
    );
  }

  function Hub() {
    const app = window.useApp();
    const user = app.user || {};
    const first = user.name ? user.name.split(' ')[0] : '';
    const cards = (GW.tools || [])
      .map(t => ({ tool: t, state: GW.toolState(user, t) }))
      .filter(x => x.state !== 'hidden');

    return e('div', { style: { maxWidth: 1320, margin: '0 auto', padding: '34px 28px 80px' } },
      e('div', { className: 'dash-hero', style: { display: 'flex', alignItems: 'center', gap: 22, marginBottom: 30 } },
        e('div', { className: 'grow' },
          e('div', { className: 'eyebrow' }, 'GarageWiz Hub'),
          e('h1', { className: 'display', style: { fontSize: 36, fontWeight: 600, margin: '4px 0 0' } }, 'Welcome back, ' + first + ' 👋'),
          e('p', { className: 'muted', style: { fontSize: 16, margin: '6px 0 0' } }, 'Pick a tool to get started. More tools are on the way.'),
        ),
        e(Mascot, { size: 110, className: 'dash-mascot' }),
      ),
      e('div', { className: 'hub-grid', style: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 } },
        cards.map(x => e(ToolCard, { key: x.tool.id, tool: x.tool, state: x.state })),
      ),
    );
  }
  window.Hub = Hub;
})();
