/* SUPERMEDIA storefront — Lista želja (wishlist) + Nalog (login + dashboard) */
const { useState: useStateAcc } = React;

const ACC_WIDE = { maxWidth: 1280, margin: '0 auto', padding: '0 24px' };

function AccHeader({ title, subtitle, onNav, titleWeight = 800 }) {
  return (
    <div style={{ background: 'linear-gradient(135deg, var(--sm-purple-50), #fff 62%)', borderBottom: '1px solid var(--sm-border)' }}>
      <div style={{ ...ACC_WIDE, padding: '30px 24px 38px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--sm-text-muted)', marginBottom: 20 }}>
          <a onClick={() => onNav({ view: 'home' })} style={{ cursor: 'pointer', color: 'var(--sm-text-muted)' }}>Početna</a>
          {I('chevron-right', 14)}<span style={{ color: 'var(--sm-text)', fontWeight: 600 }}>{title}</span>
        </div>
        <h1 style={{ fontSize: 42, fontWeight: titleWeight, margin: 0, lineHeight: 1.08, letterSpacing: '-.02em' }}>{title}</h1>
        {subtitle && <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--sm-gray-700)', margin: '12px 0 0', maxWidth: '60ch' }}>{subtitle}</p>}
      </div>
    </div>
  );
}

/* ---------- Lista želja ---------- */
function WishlistPage({ wishlist, onWish, onAdd, openProduct, onNav }) {
  const all = (window.SM_DATA && window.SM_DATA.PRODUCTS) || [];
  const items = all.filter(p => wishlist.includes(p.id));
  return (
    <div>
      <AccHeader title="Lista želja" subtitle={items.length ? `Sačuvano ${items.length} ${items.length === 1 ? 'proizvod' : 'proizvoda'} — dodaj u korpu kad budeš spreman.` : 'Sačuvaj omiljene proizvode na jednom mestu i vrati im se kad poželiš.'} onNav={onNav} />
      {items.length === 0 ? (
        <div style={{ ...ACC_WIDE, padding: '60px 24px 84px' }}>
          <div style={{ position: 'relative', maxWidth: 560, margin: '0 auto', textAlign: 'center', background: 'linear-gradient(180deg, var(--sm-purple-50), #fff 70%)', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-xl)', padding: '52px 36px 46px', boxShadow: 'var(--sm-shadow-xs)', overflow: 'hidden' }}>
            <div aria-hidden="true" style={{ position: 'absolute', top: -40, left: '50%', transform: 'translateX(-50%)', width: 240, height: 240, borderRadius: '50%', background: 'radial-gradient(circle, rgba(136,81,182,.22), transparent 68%)', filter: 'blur(10px)' }}></div>
            <div style={{ position: 'relative', display: 'inline-block', marginBottom: 8 }}>
              <img src={SM_DATA.A + '/mascot-genie.png'} alt="SuperMedia duh" style={{ height: 148, objectFit: 'contain', filter: 'drop-shadow(0 14px 22px rgba(124,84,153,.32))', animation: 'sm-float 5.5s ease-in-out infinite' }} />
              <span style={{ position: 'absolute', top: 8, right: -6, fontSize: 22, animation: 'sm-float 4s ease-in-out infinite' }}>✨</span>
              <span style={{ position: 'absolute', bottom: 28, left: -10, fontSize: 16, animation: 'sm-float 4.6s .4s ease-in-out infinite' }}>✨</span>
            </div>
            <h2 style={{ position: 'relative', fontSize: 24, fontWeight: 800, margin: '0 0 8px' }}>Tvoje želje čekaju duha</h2>
            <p style={{ position: 'relative', fontSize: 15.5, lineHeight: 1.6, color: 'var(--sm-text-muted)', margin: '0 auto 26px', maxWidth: '40ch' }}>Klikni na <span style={{ color: 'var(--sm-violet)' }}>♥</span> na bilo kom proizvodu i sačuvaj ga ovde — a duh će se postarati da ti ispuni želju.</p>
            <div style={{ position: 'relative', display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
              <Button variant="primary" size="lg" iconRight={I('arrow-right', 18)} onClick={() => onNav({ view: 'category', slug: null })}>Istraži proizvode</Button>
              <Button variant="outline" size="lg" iconLeft={I('sparkles', 18)} onClick={() => onNav({ view: 'popusti' })}>SUPER popusti</Button>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ ...ACC_WIDE, padding: '36px 24px 72px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 22 }}>
            <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 18 }}>{items.length} {items.length === 1 ? 'proizvod' : 'proizvoda'} u listi</div>
            <Button variant="outline" size="sm" iconLeft={I('shopping-cart', 16)} onClick={() => items.forEach(p => !p.soldOut && onAdd(p))}>Dodaj sve u korpu</Button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(244px, 1fr))', gap: 18 }}>
            {items.map(p => (
              <ProductCard key={p.id} p={p} onAdd={onAdd} onOpen={openProduct} onWish={onWish} wished={true} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Nalog: prijava / registracija ---------- */
function AuthPage({ onLogin, onNav }) {
  const [mode, setMode] = useStateAcc('login'); // 'login' | 'register'
  const [name, setName] = useStateAcc('');
  const [email, setEmail] = useStateAcc('');
  const [pass, setPass] = useStateAcc('');
  const [err, setErr] = useStateAcc('');
  const [busy, setBusy] = useStateAcc(false);
  const isReg = mode === 'register';
  const submit = async (e) => {
    if (e) e.preventDefault();
    const em = email.trim();
    if (isReg && !name.trim()) return setErr('Unesi ime i prezime.');
    if (!em) return setErr('Unesi email adresu.');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em)) return setErr('Email adresa nije ispravna.');
    if (!pass) return setErr('Unesi lozinku.');
    if (pass.length < 6) return setErr('Lozinka mora imati najmanje 6 karaktera.');
    setErr(''); setBusy(true);
    try {
      const r = await fetch(isReg ? '/sm-api/auth/register' : '/sm-api/auth/login', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), email: em, password: pass }),
      });
      const d = await r.json();
      if (!r.ok) { setBusy(false); return setErr(d.error || 'Greška. Pokušaj ponovo.'); }
      try { localStorage.setItem('sm_token', d.token); } catch (_) {}
      setBusy(false);
      onLogin(d.user);
    } catch (e2) { setBusy(false); setErr('Server nije dostupan. Da li je lokalni server upaljen?'); }
  };
  const gtoken = React.useRef(null);
  React.useEffect(() => {
    const cid = window.SM_DATA && window.SM_DATA.googleClientId;
    if (!cid || !(window.google && window.google.accounts && window.google.accounts.oauth2)) return;
    try {
      gtoken.current = window.google.accounts.oauth2.initTokenClient({
        client_id: cid,
        scope: 'openid email profile',
        callback: async (resp) => {
          if (!resp || !resp.access_token) { setErr('Google prijava je otkazana.'); return; }
          setBusy(true); setErr('');
          try {
            const r = await fetch('/sm-api/auth/google', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ accessToken: resp.access_token }) });
            const d = await r.json();
            if (!r.ok) { setBusy(false); return setErr(d.error || 'Google prijava nije uspela.'); }
            try { localStorage.setItem('sm_token', d.token); } catch (_) {}
            setBusy(false); onLogin(d.user);
          } catch (e) { setBusy(false); setErr('Server nije dostupan.'); }
        },
      });
    } catch (e) {}
  }, []);
  const googleLogin = () => {
    if (gtoken.current) { setErr(''); gtoken.current.requestAccessToken(); }
    else setErr('Google se još učitava — osveži stranicu (Ctrl+F5) i pokušaj ponovo.');
  };
  const perks = [['truck', '3 besplatne dostave svakog meseca'], ['gift', 'Poklon vaučer 2.000 din na start'], ['heart', 'Sačuvaj listu želja i prati porudžbine']];
  return (
    <div style={{ position: 'relative', overflow: 'hidden', background: 'linear-gradient(135deg, var(--sm-purple-50), var(--sm-bg) 70%)' }}>
      <div style={{ ...ACC_WIDE, padding: '48px 24px 72px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.05fr)', gap: 36, alignItems: 'center' }}>
          {/* left: brand pitch */}
          <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--sm-radius-xl)', background: 'linear-gradient(150deg, #3a2358 0%, #241638 58%, #180f26 100%)', color: '#fff', padding: '40px 40px 44px', minHeight: 420, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div style={{ position: 'absolute', right: -50, top: -50, width: 230, height: 230, borderRadius: '50%', background: 'radial-gradient(circle, rgba(136,81,182,.45), transparent 70%)', filter: 'blur(6px)' }}></div>
            <div style={{ position: 'absolute', left: -40, bottom: -40, width: 180, height: 180, borderRadius: '50%', background: 'radial-gradient(circle, rgba(125,84,153,.4), transparent 70%)', filter: 'blur(6px)' }}></div>
            <img src={SM_DATA.A + '/logo-white.png'} alt="SuperMedia" style={{ height: 46, alignSelf: 'flex-start', marginBottom: 26, position: 'relative' }} />
            <h2 style={{ position: 'relative', fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 32, lineHeight: 1.12, margin: 0, color: '#fff', maxWidth: '14ch' }}>Tvoj nalog, tvoje pogodnosti.</h2>
            <p style={{ position: 'relative', fontSize: 16, lineHeight: 1.6, color: 'rgba(255,255,255,.9)', margin: '14px 0 26px', maxWidth: '34ch' }}>Prijavi se i otključaj brže poručivanje, praćenje pošiljki i posebne cene.</p>
            <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 14 }}>
              {perks.map(([ic, t]) => (
                <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 16 }}>
                  <span style={{ width: 38, height: 38, flex: 'none', borderRadius: '50%', background: 'rgba(255,255,255,.16)', border: '1px solid rgba(255,255,255,.28)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I(ic, 19)}</span>
                  {t}
                </div>
              ))}
            </div>
          </div>
          {/* right: form */}
          <form onSubmit={submit} style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-xl)', padding: '34px 38px 38px', boxShadow: 'var(--sm-shadow-md)' }}>
            <div style={{ display: 'flex', gap: 6, background: 'var(--sm-gray-100)', borderRadius: 'var(--sm-radius-pill)', padding: 5, marginBottom: 26 }}>
              {[['login', 'Prijava'], ['register', 'Registracija']].map(([m, lbl]) => (
                <button key={m} type="button" onClick={() => setMode(m)} style={{ flex: 1, height: 42, border: 'none', borderRadius: 'var(--sm-radius-pill)', cursor: 'pointer', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15, background: mode === m ? '#fff' : 'transparent', color: mode === m ? 'var(--sm-primary)' : 'var(--sm-text-muted)', boxShadow: mode === m ? 'var(--sm-shadow-sm)' : 'none', transition: 'all .15s' }}>{lbl}</button>
              ))}
            </div>
            <h2 style={{ fontSize: 24, fontWeight: 800, margin: '0 0 4px' }}>{isReg ? 'Napravi nalog' : 'Dobrodošao nazad'}</h2>
            <p style={{ margin: '0 0 22px', fontSize: 14.5, color: 'var(--sm-text-muted)' }}>{isReg ? 'Par podataka i spreman si za kupovinu.' : 'Prijavi se da nastaviš tamo gde si stao.'}</p>
            {isReg && (
              <div style={{ marginBottom: 14 }}>
                <label style={accLabel}>Ime i prezime</label>
                <input value={name} onChange={e => setName(e.target.value)} placeholder="Petar Petrović" style={accInput} onFocus={e => e.currentTarget.style.borderColor = 'var(--sm-primary)'} onBlur={e => e.currentTarget.style.borderColor = 'var(--sm-border)'} />
              </div>
            )}
            <div style={{ marginBottom: 14 }}>
              <label style={accLabel}>Email adresa</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="ime@email.com" style={accInput} onFocus={e => e.currentTarget.style.borderColor = 'var(--sm-primary)'} onBlur={e => e.currentTarget.style.borderColor = 'var(--sm-border)'} />
            </div>
            <div style={{ marginBottom: isReg ? 22 : 10 }}>
              <label style={accLabel}>Lozinka</label>
              <input type="password" value={pass} onChange={e => setPass(e.target.value)} placeholder="••••••••" style={accInput} onFocus={e => e.currentTarget.style.borderColor = 'var(--sm-primary)'} onBlur={e => e.currentTarget.style.borderColor = 'var(--sm-border)'} />
            </div>
            {!isReg && (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 14, color: 'var(--sm-text-muted)', cursor: 'pointer' }}>
                  <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: 'var(--sm-primary)' }} /> Zapamti me
                </label>
                <a style={{ fontSize: 14, fontWeight: 600, color: 'var(--sm-primary)', cursor: 'pointer' }}>Zaboravljena lozinka?</a>
              </div>
            )}
            {err && <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'color-mix(in srgb, var(--sm-sale) 10%, #fff)', border: '1px solid color-mix(in srgb, var(--sm-sale) 32%, #fff)', color: 'var(--sm-sale)', borderRadius: 'var(--sm-radius-sm)', padding: '10px 14px', fontSize: 13.5, fontWeight: 600, marginBottom: 14 }}>{I('alert-circle', 16)} {err}</div>}
            <Button type="submit" variant="primary" size="lg" block disabled={busy} iconRight={I('arrow-right', 18)}>{busy ? 'Sačekaj…' : (isReg ? 'Registruj se' : 'Prijavi se')}</Button>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '22px 0' }}>
              <span style={{ flex: 1, height: 1, background: 'var(--sm-border)' }}></span>
              <span style={{ fontSize: 13, color: 'var(--sm-text-subtle)' }}>ili</span>
              <span style={{ flex: 1, height: 1, background: 'var(--sm-border)' }}></span>
            </div>
            <button type="button" onClick={googleLogin} style={{ width: '100%', height: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, background: '#fff', border: '1.5px solid var(--sm-border)', borderRadius: 'var(--sm-radius-pill)', cursor: 'pointer', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15, color: 'var(--sm-text)' }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--sm-gray-50)'} onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
              {I('mail', 18)} Nastavi sa Google nalogom
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
const accLabel = { display: 'block', fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 13.5, marginBottom: 6, color: 'var(--sm-text)' };
const accInput = { width: '100%', height: 48, border: '1.5px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', padding: '0 15px', fontFamily: 'var(--sm-font-body)', fontSize: 15, outline: 'none', boxSizing: 'border-box', background: '#fff', transition: 'border-color .15s' };

/* ---------- Nalog: dashboard (ulogovan) ---------- */
function AccountDashboard({ user, onLogout, onUpdate, onNav, wishCount }) {
  const [tab, setTab] = useStateAcc('pregled');
  const [editing, setEditing] = useStateAcc(false);
  const [pf, setPf] = useStateAcc({ name: '', phone: '', address: '', city: '', zip: '' });
  const [pBusy, setPBusy] = useStateAcc(false);
  const [pErr, setPErr] = useStateAcc('');
  const beginEdit = () => { setPf({ name: user.name || '', phone: user.phone || '', address: user.address || '', city: user.city || '', zip: user.zip || '' }); setPErr(''); setEditing(true); };
  const saveProfile = async () => {
    if (!pf.name.trim()) return setPErr('Ime i prezime ne sme biti prazno.');
    let tok = null; try { tok = localStorage.getItem('sm_token'); } catch (e) {}
    setPBusy(true); setPErr('');
    try {
      const r = await fetch('/sm-api/auth/profile', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tok }, body: JSON.stringify(pf) });
      const d = await r.json();
      if (!r.ok) { setPBusy(false); return setPErr(d.error || 'Greška pri čuvanju.'); }
      if (onUpdate) onUpdate(d.user);
      setPBusy(false); setEditing(false);
    } catch (e) { setPBusy(false); setPErr('Server nije dostupan.'); }
  };
  const [rawOrders, setRawOrders] = useStateAcc([]);
  React.useEffect(() => {
    let tok = null; try { tok = localStorage.getItem('sm_token'); } catch (e) {}
    if (!tok) return;
    fetch('/sm-api/orders', { headers: { Authorization: 'Bearer ' + tok } }).then(r => r.ok ? r.json() : null).then(d => { if (d && d.orders) setRawOrders(d.orders); }).catch(() => {});
  }, []);
  const initials = user.name.split(' ').map(s => s[0]).join('').slice(0, 2).toUpperCase();
  const orders = rawOrders.map(o => {
    const dt = new Date(o.createdAt);
    const date = ('' + dt.getDate()).padStart(2, '0') + '.' + ('' + (dt.getMonth() + 1)).padStart(2, '0') + '.' + dt.getFullYear() + '.';
    const stage = o.statusStage || 0;
    const li = stage >= 4 ? ['Isporučeno', 'delivered'] : stage >= 2 ? ['U transportu', 'transit'] : ['U obradi', 'transit'];
    return [o.num, date, li[0], o.total || 0, li[1]];
  });
  const statusTone = { delivered: ['var(--sm-success-soft)', 'var(--sm-success)'], transit: ['var(--sm-info-soft)', 'var(--sm-info)'] };
  const menu = [
    ['pregled', 'Pregled', 'layout-dashboard'],
    ['porudzbine', 'Porudžbine', 'package'],
    ['zelje', 'Lista želja', 'heart'],
    ['podaci', 'Podaci o nalogu', 'user'],
    ['adrese', 'Adrese', 'map-pin'],
  ];
  const stats = [
    ['package', 'Porudžbine', orders.length, { view: 'account' }, () => setTab('porudzbine')],
    ['heart', 'Lista želja', wishCount, { view: 'wishlist' }, null],
    ['truck', 'Besplatne dostave', '3/3', null, null],
  ];
  return (
    <div>
      <AccHeader title={`Zdravo, ${user.name.split(' ')[0]} 👋`} titleWeight={500} subtitle="Dobrodošao u svoj SuperMedia nalog. Ovde pratiš porudžbine, čuvaš želje i upravljaš podacima." onNav={onNav} />
      <div style={{ ...ACC_WIDE, padding: '32px 24px 72px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '270px minmax(0,1fr)', gap: 28, alignItems: 'start' }}>
          {/* sidebar */}
          <aside style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-xl)', padding: 18, boxShadow: 'var(--sm-shadow-xs)', position: 'sticky', top: 76 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '6px 8px 18px', borderBottom: '1px solid var(--sm-border)', marginBottom: 14 }}>
              <span style={{ width: 52, height: 52, flex: 'none', borderRadius: '50%', background: 'linear-gradient(135deg, var(--sm-primary), var(--sm-violet))', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 19 }}>{initials}</span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 16, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name}</div>
                <div style={{ fontSize: 13, color: 'var(--sm-text-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.email}</div>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {menu.map(([k, lbl, ic]) => {
                const on = tab === k;
                return (
                  <button key={k} onClick={() => k === 'zelje' ? onNav({ view: 'wishlist' }) : setTab(k)} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', padding: '11px 14px', border: 'none', borderRadius: 'var(--sm-radius-md)', cursor: 'pointer', background: on ? 'var(--sm-purple-50)' : 'transparent', color: on ? 'var(--sm-primary)' : 'var(--sm-text)', fontFamily: 'var(--sm-font-display)', fontWeight: on ? 700 : 600, fontSize: 15, transition: 'background .15s' }}
                    onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--sm-gray-50)'; }}
                    onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                    {I(ic, 18)} {lbl}
                    {k === 'zelje' && wishCount > 0 && <span style={{ marginLeft: 'auto', minWidth: 20, height: 20, padding: '0 6px', borderRadius: 10, background: 'var(--sm-violet)', color: '#fff', fontSize: 12, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{wishCount}</span>}
                  </button>
                );
              })}
              <button onClick={onLogout} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', padding: '11px 14px', border: 'none', borderRadius: 'var(--sm-radius-md)', cursor: 'pointer', background: 'transparent', color: 'var(--sm-sale)', fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 15, marginTop: 6 }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--sm-gray-50)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                {I('log-out', 18)} Odjavi se
              </button>
            </div>
          </aside>

          {/* main */}
          <div style={{ minWidth: 0 }}>
            {tab === 'pregled' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0,1fr))', gap: 16 }}>
                  {stats.map(([ic, lbl, val, , onClick]) => (
                    <button key={lbl} onClick={onClick || undefined} style={{ textAlign: 'left', background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-xl)', padding: '22px 24px', boxShadow: 'var(--sm-shadow-xs)', cursor: onClick ? 'pointer' : 'default', transition: 'transform .15s, box-shadow .15s' }}
                      onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.boxShadow = 'var(--sm-shadow-md)'; }}
                      onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'var(--sm-shadow-xs)'; }}>
                      <span style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--sm-purple-50)', color: 'var(--sm-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>{I(ic, 22)}</span>
                      <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 500, fontSize: 30, lineHeight: 1 }}>{val}</div>
                      <div style={{ fontSize: 14, color: 'var(--sm-text-muted)', marginTop: 6 }}>{lbl}</div>
                    </button>
                  ))}
                </div>
                <MemberPerks onShop={() => onNav({ view: 'category', slug: null })} />
                <OrdersCard orders={orders} statusTone={statusTone} onShop={() => onNav({ view: 'category', slug: null })} />
              </div>
            )}
            {tab === 'porudzbine' && <OrdersCard orders={orders} statusTone={statusTone} full onShop={() => onNav({ view: 'category', slug: null })} />}
            {tab === 'podaci' && (
              <Panel title="Podaci o nalogu" desc="Tvoji lični podaci za bržu naplatu i isporuku.">
                {editing ? (
                  <React.Fragment>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <EditField label="Ime i prezime" value={pf.name} onChange={v => setPf(s => ({ ...s, name: v }))} placeholder="Petar Petrović" />
                      <ReadField label="Email" value={user.email} />
                      <EditField label="Telefon" value={pf.phone} onChange={v => setPf(s => ({ ...s, phone: v }))} placeholder="+381 6x xxx xxx" />
                      <EditField label="Ulica i broj" value={pf.address} onChange={v => setPf(s => ({ ...s, address: v }))} placeholder="npr. Knez Mihailova 1" />
                      <EditField label="Grad" value={pf.city} onChange={v => setPf(s => ({ ...s, city: v }))} placeholder="Beograd" />
                      <EditField label="Poštanski broj" value={pf.zip} onChange={v => setPf(s => ({ ...s, zip: v }))} placeholder="11000" />
                    </div>
                    {pErr && <div style={{ color: 'var(--sm-sale)', fontSize: 13.5, fontWeight: 600, marginTop: 14 }}>{pErr}</div>}
                    <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
                      <Button variant="primary" size="md" disabled={pBusy} onClick={saveProfile} iconLeft={I('check', 16)}>{pBusy ? 'Čuvanje…' : 'Sačuvaj'}</Button>
                      <Button variant="ghost" size="md" onClick={() => { setEditing(false); setPErr(''); }}>Otkaži</Button>
                    </div>
                  </React.Fragment>
                ) : (
                  <React.Fragment>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <ReadField label="Ime i prezime" value={user.name} />
                      <ReadField label="Email" value={user.email} />
                      <ReadField label="Telefon" value={user.phone || 'Nije uneto'} />
                      <ReadField label="Datum registracije" value={user.createdAt ? new Date(user.createdAt).toLocaleDateString('sr-RS') : '—'} />
                      <ReadField label="Adresa" value={user.address ? (user.address + (user.city ? ', ' + (user.zip ? user.zip + ' ' : '') + user.city : '')) : 'Nije uneto'} />
                    </div>
                    <Button variant="outline" size="md" style={{ marginTop: 22 }} iconLeft={I('pencil', 16)} onClick={beginEdit}>Izmeni podatke</Button>
                  </React.Fragment>
                )}
              </Panel>
            )}
            {tab === 'adrese' && (
              <Panel title="Adrese za isporuku" desc="Sačuvane adrese za bržu kupovinu.">
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px,1fr))', gap: 16 }}>
                  {user.address && (
                    <div style={{ border: '1.5px solid var(--sm-primary)', borderRadius: 'var(--sm-radius-lg)', padding: '20px 22px', position: 'relative' }}>
                      <Badge tone="purple" size="sm" style={{ position: 'absolute', top: 16, right: 16 }}>Primarna</Badge>
                      <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 16, marginBottom: 6 }}>{user.name}</div>
                      <div style={{ fontSize: 14.5, lineHeight: 1.6, color: 'var(--sm-text-muted)' }}>{user.address}<br />{(user.zip ? user.zip + ' ' : '') + (user.city || '')}{user.phone ? <React.Fragment><br />{user.phone}</React.Fragment> : null}</div>
                    </div>
                  )}
                  <button onClick={() => { beginEdit(); setTab('podaci'); }} style={{ border: '1.5px dashed var(--sm-purple-300)', borderRadius: 'var(--sm-radius-lg)', padding: '20px 22px', background: 'var(--sm-purple-50)', color: 'var(--sm-primary)', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15, minHeight: 140 }}>
                    {I('plus', 24)} {user.address ? 'Izmeni adresu' : 'Dodaj adresu'}
                  </button>
                </div>
                {!user.address && <div style={{ marginTop: 14, fontSize: 14, color: 'var(--sm-text-muted)' }}>Još nemaš sačuvanu adresu — dodaj je za bržu kupovinu.</div>}
              </Panel>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function MemberPerks({ onShop }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.05fr) minmax(0,1fr)', gap: 16 }}>
      {/* welcome voucher */}
      <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--sm-radius-xl)', background: 'linear-gradient(135deg, var(--sm-primary), var(--sm-violet))', color: '#fff', padding: '26px 28px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ position: 'absolute', right: -28, top: -28, width: 130, height: 130, borderRadius: '50%', background: 'rgba(255,255,255,.12)' }}></div>
        <div style={{ position: 'absolute', left: '38%', top: 0, bottom: 0, width: 0, borderLeft: '2px dashed rgba(255,255,255,.0)' }}></div>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <span style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,.18)', border: '1px solid rgba(255,255,255,.3)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I('gift', 20)}</span>
          <span style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.14em', fontSize: 12, color: 'rgba(255,255,255,.9)' }}>Poklon dobrodošlice</span>
        </div>
        <div style={{ position: 'relative', fontFamily: 'var(--sm-font-body)', fontWeight: 800, fontSize: 40, lineHeight: 1 }}>2.000 <span style={{ fontSize: 18 }}>din.</span></div>
        <p style={{ position: 'relative', margin: '8px 0 16px', fontSize: 14, lineHeight: 1.55, color: 'rgba(255,255,255,.9)' }}>Vaučer važi na porudžbine preko <b>20.000 din</b>. Automatski se primenjuje u korpi.</p>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginTop: 'auto' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(255,255,255,.16)', border: '1px dashed rgba(255,255,255,.5)', borderRadius: 'var(--sm-radius-pill)', padding: '7px 16px', fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 15, letterSpacing: '.06em' }}>{I('ticket', 16)} DOBRODOSLI2000</span>
          <Button variant="light" size="sm" onClick={onShop} iconRight={I('arrow-right', 16)}>Iskoristi</Button>
        </div>
      </div>
      {/* free delivery perk */}
      <div style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-xl)', padding: '26px 28px', boxShadow: 'var(--sm-shadow-xs)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <span style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--sm-purple-50)', color: 'var(--sm-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I('truck', 20)}</span>
          <span style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.14em', fontSize: 12, color: 'var(--sm-text-muted)' }}>Pogodnost člana</span>
        </div>
        <h3 style={{ margin: '0 0 4px', fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 19 }}>Besplatna dostava</h3>
        <p style={{ margin: '0 0 18px', fontSize: 14, lineHeight: 1.55, color: 'var(--sm-text-muted)' }}>Prve <b>3 porudžbine</b> svakog meseca dostavljamo potpuno besplatno.</p>
        <div style={{ marginTop: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
            <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, color: 'var(--sm-text)' }}>Iskorišćeno ovog meseca</span>
            <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 15, color: 'var(--sm-primary)' }}>0 / 3</span>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[0, 1, 2].map(i => (
              <span key={i} style={{ flex: 1, height: 9, borderRadius: 5, background: 'var(--sm-purple-100)', border: '1px solid var(--sm-purple-200)' }}></span>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 14, fontSize: 13.5, color: 'var(--sm-success)', fontFamily: 'var(--sm-font-display)', fontWeight: 700 }}>{I('check-circle', 16)} 3 besplatne dostave su ti na raspolaganju.</div>
        </div>
      </div>
    </div>
  );
}

function Panel({ title, desc, children }) {
  return (
    <div style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-xl)', padding: '28px 30px', boxShadow: 'var(--sm-shadow-xs)' }}>
      <h2 style={{ fontSize: 21, fontWeight: 800, margin: '0 0 4px' }}>{title}</h2>
      {desc && <p style={{ margin: '0 0 22px', fontSize: 14.5, color: 'var(--sm-text-muted)' }}>{desc}</p>}
      {children}
    </div>
  );
}
function ReadField({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--sm-text-muted)', marginBottom: 5 }}>{label}</div>
      <div style={{ background: 'var(--sm-gray-50)', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', padding: '12px 15px', fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 15 }}>{value}</div>
    </div>
  );
}
function EditField({ label, value, onChange, placeholder }) {
  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--sm-text-muted)', marginBottom: 5 }}>{label}</div>
      <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder || ''} style={{ width: '100%', height: 46, border: '1.5px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', padding: '0 14px', fontFamily: 'var(--sm-font-body)', fontSize: 15, outline: 'none', boxSizing: 'border-box', background: '#fff' }} onFocus={e => e.currentTarget.style.borderColor = 'var(--sm-primary)'} onBlur={e => e.currentTarget.style.borderColor = 'var(--sm-border)'} />
    </div>
  );
}
function OrdersCard({ orders, statusTone, full, onShop }) {
  return (
    <Panel title={full ? 'Sve porudžbine' : 'Poslednje porudžbine'} desc={full ? 'Pregled svih tvojih porudžbina i njihovih statusa.' : null}>
      {orders.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '20px 0 8px', color: 'var(--sm-text-muted)' }}>
          <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 16, color: 'var(--sm-text)' }}>Još nemaš porudžbina</div>
          <div style={{ fontSize: 14, margin: '4px 0 16px' }}>Kad poručiš, ovde pratiš status u realnom vremenu.</div>
          <Button variant="primary" size="md" onClick={onShop} iconRight={I('arrow-right', 16)}>Počni kupovinu</Button>
        </div>
      ) : (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {orders.map(([id, date, status, total, tone], i) => {
          const [bg, col] = statusTone[tone];
          return (
            <div key={id} style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', padding: '16px 0', borderTop: i ? '1px solid var(--sm-border)' : 'none' }}>
              <span style={{ width: 44, height: 44, flex: 'none', borderRadius: 12, background: 'var(--sm-purple-50)', color: 'var(--sm-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I('package', 21)}</span>
              <div style={{ minWidth: 120 }}>
                <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15.5 }}>{id}</div>
                <div style={{ fontSize: 13, color: 'var(--sm-text-muted)' }}>{date}</div>
              </div>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: bg, color: col, borderRadius: 'var(--sm-radius-pill)', padding: '5px 12px', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 13 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: col }}></span>{status}
              </span>
              <div style={{ marginLeft: 'auto', fontFamily: 'var(--sm-font-body)', fontWeight: 800, fontSize: 17, color: 'var(--sm-price)' }}>{fmt(total)} <span style={{ fontSize: 12 }}>din.</span></div>
              <button style={{ flex: 'none', background: 'none', border: '1.5px solid var(--sm-border)', borderRadius: 'var(--sm-radius-pill)', height: 36, padding: '0 16px', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, color: 'var(--sm-text)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                Detalji {I('chevron-right', 15)}
              </button>
            </div>
          );
        })}
      </div>
      )}
    </Panel>
  );
}

/* ---------- router entry ---------- */
function AccountPage({ user, onLogin, onLogout, onUpdate, onNav, wishCount }) {
  return user
    ? <AccountDashboard user={user} onLogout={onLogout} onUpdate={onUpdate} onNav={onNav} wishCount={wishCount} />
    : <AuthPage onLogin={onLogin} onNav={onNav} />;
}

Object.assign(window, { WishlistPage, AccountPage });
