// profile-user.jsx — Profil settings (user)

const { useState: useStatePU } = React;

function ProfileUserPage({ onNav, user }) {
  const [tab, setTab] = useStatePU('personal');
  const [Toast, toast] = useToast();
  const [confirmDel, setConfirmDel] = useStatePU(false);
  const [addrModal, setAddrModal] = useStatePU(false);

  const tabs = [
    { id: 'personal', ico: '👤', label: 'Date personale' },
    { id: 'security', ico: '🔒', label: 'Securitate' },
    { id: 'notif', ico: '🔔', label: 'Notificări' },
    { id: 'addr', ico: '📍', label: 'Adrese' },
    { id: 'pref', ico: '⚙️', label: 'Preferințe' },
  ];

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh' }}>
      <DashSidebar active="profile" onNav={onNav} user={user} />
      <main style={{ padding: '32px 48px 100px', overflowY: 'auto', background: 'var(--bg-1)' }} className="dash-main">
        {/* Header card */}
        <div className="card-glass" style={{ padding: 28, marginBottom: 24, position: 'relative', overflow: 'hidden' }}>
          <div className="mesh" style={{ inset: 'auto -10% -50% auto', width: '50%', height: '180%', opacity: 0.5 }} />
          <div style={{ position: 'relative', zIndex: 2, display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap' }}>
            <div style={{ position: 'relative' }}>
              <div style={{ width: 96, height: 96, borderRadius: 999, background: 'linear-gradient(135deg, var(--accent-2), var(--accent-1))', display: 'grid', placeItems: 'center', fontSize: 36, fontWeight: 700, color: '#0A0A0F' }}>
                {(user?.name || 'AM').split(' ').map(s => s[0]).slice(0, 2).join('')}
              </div>
              <button className="btn btn-glass btn-sm" style={{ position: 'absolute', bottom: -6, right: -6, padding: '4px 8px', fontSize: 10 }}>📷</button>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <h1 className="display" style={{ fontSize: 30, margin: 0 }}>{user?.name || 'Andra Mihăescu'}</h1>
                <span className="pill" style={{ background: 'rgba(82,242,15,.12)', borderColor: 'rgba(82,242,15,.3)', color: 'var(--accent-1)', fontSize: 11 }}>● DIAMOND</span>
              </div>
              <div style={{ fontSize: 14, color: 'var(--txt-2)', marginTop: 6 }}>{user?.email || 'andra.m@4uagency.ro'}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 4 }}>● Membru din 14 ianuarie 2024 · 2 ani și 3 luni</div>
            </div>
            <button className="btn btn-glass">Schimbă fotoul</button>
          </div>
        </div>

        {/* Tabs sticky */}
        <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'rgba(14,14,14,0.92)', backdropFilter: 'blur(20px)', padding: '12px 0', borderBottom: '.5px solid var(--line-soft)', marginBottom: 24, marginLeft: -48, marginRight: -48, paddingLeft: 48, paddingRight: 48 }}>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {tabs.map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} className="btn btn-sm" style={{
                background: tab === t.id ? 'var(--accent-1)' : 'transparent',
                color: tab === t.id ? '#0A0A0F' : 'var(--txt-2)',
                border: tab === t.id ? 'none' : '.5px solid var(--line)',
                fontWeight: tab === t.id ? 600 : 400,
              }}>{t.ico} {t.label}</button>
            ))}
          </div>
        </div>

        {tab === 'personal' && <PersonalTab user={user} toast={toast} />}
        {tab === 'security' && <SecurityTab toast={toast} onDelete={() => setConfirmDel(true)} />}
        {tab === 'notif' && <NotifTab toast={toast} />}
        {tab === 'addr' && <AddressTab onAdd={() => setAddrModal(true)} toast={toast} />}
        {tab === 'pref' && <PrefTab toast={toast} />}

        {/* Sticky save bar */}
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(calc(-50% + 130px))',
          background: 'rgba(8,8,12,0.95)', backdropFilter: 'blur(20px)', borderRadius: 14,
          padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 12,
          border: '.5px solid var(--line)', boxShadow: '0 12px 40px rgba(0,0,0,.5)', zIndex: 50,
        }} className="save-bar">
          <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>● 0 modificări</span>
          <button onClick={() => toast('Modificările au fost salvate')} className="btn btn-primary btn-sm">Salvează toate modificările</button>
        </div>
      </main>

      {/* Delete confirm modal */}
      {confirmDel && (
        <div onClick={() => setConfirmDel(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', backdropFilter: 'blur(8px)', zIndex: 200, display: 'grid', placeItems: 'center', padding: 24 }}>
          <div onClick={(e) => e.stopPropagation()} className="card-glass" style={{ maxWidth: 460, width: '100%', padding: 28, borderColor: '#ef4444' }}>
            <div style={{ fontSize: 36 }}>⚠️</div>
            <div className="display" style={{ fontSize: 22, marginTop: 12 }}>Ești sigură?</div>
            <p style={{ color: 'var(--txt-2)', fontSize: 14, marginTop: 8 }}>Această acțiune este permanentă. Toate datele tale, punctele 4U și istoricul vor fi șterse definitiv.</p>
            <div style={{ marginTop: 20, display: 'flex', gap: 8 }}>
              <button className="btn btn-glass" style={{ flex: 1 }} onClick={() => setConfirmDel(false)}>Anulează</button>
              <button className="btn" style={{ flex: 1, background: '#ef4444', color: '#fff' }} onClick={() => { setConfirmDel(false); toast('Cerere de ștergere trimisă (mock)'); }}>Șterge contul</button>
            </div>
          </div>
        </div>
      )}

      {/* Address modal */}
      {addrModal && (
        <div onClick={() => setAddrModal(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)', zIndex: 200, display: 'grid', placeItems: 'center', padding: 24 }}>
          <div onClick={(e) => e.stopPropagation()} className="card-glass" style={{ maxWidth: 540, width: '100%', padding: 28 }}>
            <div className="display" style={{ fontSize: 22 }}>Adaugă adresă</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 }}>
              <PuField label="Etichetă" placeholder="Ex: Acasă" />
              <PuField label="Țară" type="select" options={['🇷🇴 România', '🇬🇧 UK', '🇩🇪 Germania', '🇮🇹 Italia', '🇪🇸 Spania']} />
              <PuField label="Oraș" placeholder="București" />
              <PuField label="Cod poștal" placeholder="010494" />
              <div style={{ gridColumn: 'span 2' }}><PuField label="Stradă și număr" placeholder="Str. Polonă, nr. 38" /></div>
              <div style={{ gridColumn: 'span 2' }}><PuField label="Detalii (bloc, ap, etaj)" placeholder="Opțional" /></div>
            </div>
            <div style={{ marginTop: 20, display: 'flex', gap: 8 }}>
              <button className="btn btn-glass" style={{ flex: 1 }} onClick={() => setAddrModal(false)}>Anulează</button>
              <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => { setAddrModal(false); toast('Adresă adăugată'); }}>Salvează</button>
            </div>
          </div>
        </div>
      )}

      {Toast}
    </div>
  );
}

function PuField({ label, type = 'text', placeholder, value, prefix, options, disabled, max }) {
  const [v, setV] = useStatePU(value || '');
  return (
    <div>
      <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', display: 'block', marginBottom: 6 }}>{label.toUpperCase()}</label>
      {type === 'select' ? (
        <select className="input" style={{ height: 40 }} disabled={disabled}>{options.map(o => <option key={o}>{o}</option>)}</select>
      ) : type === 'textarea' ? (
        <div>
          <textarea className="input" style={{ minHeight: 80, padding: 10, resize: 'vertical' }} placeholder={placeholder} maxLength={max} value={v} onChange={(e) => setV(e.target.value)} />
          {max && <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', textAlign: 'right', marginTop: 4 }}>{v.length}/{max}</div>}
        </div>
      ) : prefix ? (
        <div style={{ display: 'flex', alignItems: 'center', background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 8, paddingLeft: 12 }}>
          <span className="mono" style={{ fontSize: 13, color: 'var(--txt-3)' }}>{prefix}</span>
          <input type={type} className="input" style={{ border: 0, background: 'transparent', height: 38 }} placeholder={placeholder} value={v} onChange={(e) => setV(e.target.value)} disabled={disabled} />
        </div>
      ) : (
        <input type={type} className="input" style={{ height: 40 }} placeholder={placeholder} value={v} onChange={(e) => setV(e.target.value)} disabled={disabled} />
      )}
    </div>
  );
}

function PersonalTab({ user, toast }) {
  return (
    <div className="card" style={{ padding: 28 }}>
      <div className="display" style={{ fontSize: 20, marginBottom: 20 }}>Date personale</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="prof-grid">
        <PuField label="Nume" value={(user?.name || 'Andra Mihăescu').split(' ')[1] || ''} />
        <PuField label="Prenume" value={(user?.name || 'Andra Mihăescu').split(' ')[0]} />
        <div style={{ gridColumn: 'span 2' }}>
          <PuField label="Email" value={user?.email || 'andra.m@4uagency.ro'} disabled />
          <a className="mono" style={{ fontSize: 10, color: 'var(--accent-1)', marginTop: 4, display: 'inline-block' }}>Schimbă email →</a>
        </div>
        <PuField label="Telefon" prefix="+40 " placeholder="723 456 789" />
        <PuField label="Username TikTok" prefix="@" placeholder="andra.m" />
        <PuField label="Data nașterii" type="date" />
        <PuField label="Țară" type="select" options={['🇷🇴 România', '🇬🇧 UK', '🇩🇪 Germania', '🇮🇹 Italia', '🇪🇸 Spania', '🇫🇷 Franța', '🇵🇹 Portugalia', '🇳🇱 Olanda']} />
        <PuField label="Oraș" placeholder="București" />
        <div />
        <div style={{ gridColumn: 'span 2' }}>
          <PuField label="Bio scurt" type="textarea" placeholder="Spune-ne în câteva cuvinte despre tine..." max={200} />
        </div>
      </div>
      <div style={{ marginTop: 24, display: 'flex', gap: 8 }}>
        <button className="btn btn-primary" onClick={() => toast('Modificările au fost salvate')}>Salvează modificările</button>
        <button className="btn btn-glass">Anulează</button>
      </div>
      <style>{`@media (max-width: 800px) { .prof-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function SecurityTab({ toast, onDelete }) {
  const [s2fa, setS2fa] = useStatePU(true);
  const sessions = [
    { browser: 'Chrome 124 · Mac', loc: 'București, RO', last: 'Activ acum', current: true },
    { browser: 'Safari iOS', loc: 'București, RO', last: 'Acum 2 ore' },
    { browser: 'Firefox 125 · Win', loc: 'Cluj-Napoca, RO', last: 'Acum 3 zile' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div className="card" style={{ padding: 24 }}>
        <div className="display" style={{ fontSize: 18 }}>Schimbă parola</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginTop: 16 }} className="pwd-grid">
          <PuField label="Parola curentă" type="password" placeholder="••••••••" />
          <PuField label="Parolă nouă" type="password" placeholder="Min. 8 caractere" />
          <PuField label="Confirmare" type="password" placeholder="••••••••" />
        </div>
        <button className="btn btn-primary btn-sm" style={{ marginTop: 16 }} onClick={() => toast('Parolă actualizată')}>Actualizează parola</button>
        <style>{`@media (max-width: 800px) { .pwd-grid { grid-template-columns: 1fr !important; } }`}</style>
      </div>

      <div className="card" style={{ padding: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="display" style={{ fontSize: 18 }}>Autentificare în 2 pași (2FA)</div>
            <p style={{ fontSize: 13, color: 'var(--txt-2)', marginTop: 6, maxWidth: 480 }}>Adaugă un strat extra de protecție prin cod SMS sau aplicație Authenticator.</p>
          </div>
          <Toggle on={s2fa} onChange={setS2fa} />
        </div>
      </div>

      <div className="card" style={{ padding: 24 }}>
        <div className="display" style={{ fontSize: 18 }}>Sesiuni active</div>
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {sessions.map((s, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, background: 'var(--bg-2)', borderRadius: 8, border: '.5px solid var(--line)' }}>
              <span style={{ fontSize: 18 }}>{s.current ? '🟢' : '⚪'}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13 }}>{s.browser} {s.current && <span className="mono" style={{ fontSize: 10, color: 'var(--accent-1)', marginLeft: 8 }}>● ACEASTA</span>}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginTop: 2 }}>{s.loc} · {s.last}</div>
              </div>
              {!s.current && <button className="btn btn-glass btn-sm" onClick={() => toast('Sesiune terminată')}>Termină</button>}
            </div>
          ))}
        </div>
      </div>

      <div className="card" style={{ padding: 24, borderColor: '#ef4444' + '60' }}>
        <div className="display" style={{ fontSize: 18, color: '#ef4444' }}>Șterge contul</div>
        <p style={{ fontSize: 13, color: 'var(--txt-2)', marginTop: 6 }}>Toate datele tale vor fi șterse definitiv. Punctele 4U vor fi anulate.</p>
        <button className="btn btn-sm" style={{ marginTop: 12, background: '#ef4444', color: '#fff' }} onClick={onDelete}>Șterge contul permanent</button>
      </div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 44, height: 24, borderRadius: 999, padding: 2, border: 0,
      background: on ? 'var(--accent-1)' : 'var(--bg-3)', cursor: 'pointer', transition: 'all .2s', flexShrink: 0,
    }}>
      <div style={{ width: 20, height: 20, borderRadius: 999, background: '#fff', transform: on ? 'translateX(20px)' : 'translateX(0)', transition: 'transform .2s' }} />
    </button>
  );
}

function NotifTab({ toast }) {
  const [items, setItems] = useStatePU([
    { id: 'em1', label: 'Email — actualizare puncte lunare', desc: 'Vei primi un email pe 1 al fiecărei luni cu rezumatul punctelor', on: true },
    { id: 'em2', label: 'Email — produse noi în magazin', desc: 'Notificări săptămânale cu produse adăugate', on: true },
    { id: 'em3', label: 'Email — articole blog noi', desc: 'Trimitem articole de educație TikTok', on: false },
    { id: 'em4', label: 'Email — evenimente 4U & meciuri', desc: 'Invitații la meciuri oficiale și evenimente fizice', on: true },
    { id: 'pu1', label: 'Push browser — alerte expirare puncte', desc: 'Te avertizăm cu 7 și 1 zi înainte de expirare', on: true },
    { id: 'sm1', label: 'SMS — opțional', desc: 'Costuri suplimentare pot aplica', on: false },
  ]);
  const [freq, setFreq] = useStatePU('daily');

  return (
    <div className="card" style={{ padding: 28 }}>
      <div className="display" style={{ fontSize: 20, marginBottom: 20 }}>Preferințe notificări</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {items.map((it, i) => (
          <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 0', borderBottom: i < items.length - 1 ? '.5px solid var(--line-soft)' : 'none' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{it.label}</div>
              <div style={{ fontSize: 12, color: 'var(--txt-3)', marginTop: 2 }}>{it.desc}</div>
            </div>
            <Toggle on={it.on} onChange={(v) => setItems(arr => arr.map(a => a.id === it.id ? { ...a, on: v } : a))} />
          </div>
        ))}
      </div>

      <div style={{ marginTop: 28, padding: 16, background: 'var(--bg-2)', borderRadius: 10 }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 10, letterSpacing: '0.1em' }}>FRECVENȚĂ EMAILURI</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {[['imm', 'Imediat'], ['daily', 'Zilnic (digest)'], ['weekly', 'Săptămânal']].map(([id, l]) => (
            <button key={id} onClick={() => setFreq(id)} className="btn btn-sm" style={{
              background: freq === id ? 'var(--accent-1)' : 'transparent',
              color: freq === id ? '#0A0A0F' : 'var(--txt-2)',
              border: freq === id ? 'none' : '.5px solid var(--line)',
            }}>{l}</button>
          ))}
        </div>
      </div>

      <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={() => toast('Notificări salvate')}>Salvează preferințe</button>
    </div>
  );
}

function AddressTab({ onAdd, toast }) {
  const [addrs, setAddrs] = useStatePU([
    { id: 1, label: 'Acasă', street: 'Str. Polonă 38, Sc. A, Ap. 12', city: 'București, 010494', country: '🇷🇴 România', main: true },
    { id: 2, label: 'Birou', street: 'Calea Victoriei 120, Et. 4', city: 'București, 010091', country: '🇷🇴 România', main: false },
  ]);
  const setMain = (id) => setAddrs(arr => arr.map(a => ({ ...a, main: a.id === id })));
  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {addrs.map(a => (
          <div key={a.id} className="card" style={{ padding: 20, display: 'flex', gap: 16, alignItems: 'flex-start' }}>
            <button onClick={() => setMain(a.id)} style={{
              width: 18, height: 18, borderRadius: 999, padding: 0, marginTop: 4,
              border: '.5px solid', borderColor: a.main ? 'var(--accent-1)' : 'var(--line)',
              background: a.main ? 'var(--accent-1)' : 'transparent', cursor: 'pointer',
            }} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 15, fontWeight: 500 }}>{a.label}</span>
                {a.main && <span className="pill" style={{ fontSize: 9, background: 'rgba(82,242,15,.12)', borderColor: 'rgba(82,242,15,.3)', color: 'var(--accent-1)' }}>● PRINCIPALĂ</span>}
              </div>
              <div style={{ fontSize: 13, color: 'var(--txt-2)', marginTop: 6, lineHeight: 1.6 }}>{a.street}<br/>{a.city}<br/>{a.country}</div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn btn-glass btn-sm">Editează</button>
              <button className="btn btn-glass btn-sm" onClick={() => { setAddrs(arr => arr.filter(x => x.id !== a.id)); toast('Adresă ștearsă'); }}>Șterge</button>
            </div>
          </div>
        ))}
      </div>
      <button onClick={onAdd} className="btn btn-glass" style={{ width: '100%', marginTop: 16, padding: 20, borderStyle: 'dashed' }}>+ Adaugă adresă nouă</button>
    </div>
  );
}

function PrefTab({ toast }) {
  const [theme, setTheme] = useStatePU('dark');
  const [news, setNews] = useStatePU(true);
  const [chips, setChips] = useStatePU(['Tehnologie', 'Călătorii']);
  const allChips = ['Tehnologie', 'Modă', 'Călătorii', 'Experiențe', 'Cosmetice'];
  const toggle = (c) => setChips(arr => arr.includes(c) ? arr.filter(x => x !== c) : [...arr, c]);
  return (
    <div className="card" style={{ padding: 28 }}>
      <div className="display" style={{ fontSize: 20, marginBottom: 20 }}>Preferințe</div>

      <div style={{ marginBottom: 24 }}>
        <PuField label="Limba site" type="select" options={['🇷🇴 Română', '🇬🇧 English', '🇮🇹 Italiano', '🇪🇸 Español', '🇩🇪 Deutsch']} />
      </div>

      <div style={{ marginBottom: 24 }}>
        <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', display: 'block', marginBottom: 10 }}>TEMA</label>
        <div style={{ display: 'flex', gap: 8 }}>
          {[['dark', '🌙 Dark'], ['light', '☀️ Light'], ['auto', '🔄 Auto (sistem)']].map(([id, l]) => (
            <button key={id} onClick={() => setTheme(id)} className="btn btn-sm" style={{
              background: theme === id ? 'var(--accent-1)' : 'transparent',
              color: theme === id ? '#0A0A0F' : 'var(--txt-2)',
              border: theme === id ? 'none' : '.5px solid var(--line)',
            }}>{l}</button>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 24 }}>
        <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', display: 'block', marginBottom: 10 }}>CATEGORII PREFERATE PRODUSE</label>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {allChips.map(c => (
            <button key={c} onClick={() => toggle(c)} className="btn btn-sm" style={{
              background: chips.includes(c) ? 'rgba(82,242,15,.12)' : 'transparent',
              color: chips.includes(c) ? 'var(--accent-1)' : 'var(--txt-2)',
              border: '.5px solid', borderColor: chips.includes(c) ? 'rgba(82,242,15,.4)' : 'var(--line)',
            }}>{chips.includes(c) ? '✓ ' : ''}{c}</button>
          ))}
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: 14, background: 'var(--bg-2)', borderRadius: 8 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500 }}>Newsletter săptămânal</div>
          <div style={{ fontSize: 12, color: 'var(--txt-3)', marginTop: 2 }}>Sfaturi TikTok și actualizări 4U</div>
        </div>
        <Toggle on={news} onChange={setNews} />
      </div>

      <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={() => toast('Preferințe salvate')}>Salvează preferințe</button>
    </div>
  );
}

window.ProfileUserPage = ProfileUserPage;
