// HIFA OIL Loyalty — Settings screen + detail flows
// Profil edit, e-mail change, password change, terms, FAQ link,
// rate-us, and deactivate confirmation.
const { useState: useSet } = React;

const FAQ_URL = 'https://www.hifaoil.ba/';

const TERMS = [
  ['1. Opće odredbe', 'Korištenjem HIFA OIL ISOMAX Loyalty aplikacije prihvatate ove uslove korištenja. Aplikacija omogućava praćenje stanja loyalty kartice, prikupljanje i trošenje bodova te pregled pogodnosti.'],
  ['2. Korisnički račun', 'Korisnik je odgovoran za tačnost unesenih podataka i za čuvanje pristupnih podataka. HIFA OIL zadržava pravo deaktivacije računa u slučaju zloupotrebe.'],
  ['3. Loyalty bodovi', 'Bodovi (litri) se prikupljaju prilikom kupovine goriva i proizvoda na HIFA OIL prodajnim mjestima. Bodovi nemaju novčanu vrijednost i ne mogu se zamijeniti za gotovinu.'],
  ['4. Zaštita podataka', 'Lični podaci se obrađuju u skladu sa važećim propisima o zaštiti podataka. Podaci se koriste isključivo u svrhu funkcionisanja loyalty programa.'],
  ['5. Izmjene uslova', 'HIFA OIL zadržava pravo izmjene ovih uslova. O značajnim izmjenama korisnici će biti obaviješteni putem aplikacije.'],
];

// ── small reusable sheet header note ──
function SheetForm({ children }) {
  return <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>{children}</div>;
}

// ── Rate us (placeholder for ocjenite_nas page) ──
function RateSheet({ open, onClose }) {
  const [stars, setStars] = useSet(0);
  return (
    <Sheet open={open} onClose={onClose} title="Ocijenite nas">
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, paddingBottom: 6 }}>
        <LogoMark size={52} />
        <p className="t-body" style={{ color: 'var(--text-2)', textAlign: 'center', margin: 0, maxWidth: 280 }}>
          Vaše mišljenje nam je važno. Kako biste ocijenili HIFA OIL Loyalty aplikaciju?</p>
        <div style={{ display: 'flex', gap: 8 }}>
          {[1, 2, 3, 4, 5].map(n => (
            <Pressable key={n} onClick={() => setStars(n)}>
              <Icon name="star" size={36} color="var(--hifa-gold)" fill={n <= stars ? 'var(--hifa-gold)' : 'transparent'} stroke={2} />
            </Pressable>
          ))}
        </div>
        <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
          <Button full icon="apple" onClick={onClose}>Ocijeni na App Store</Button>
          <Button full variant="dark" icon="play" onClick={onClose}>Ocijeni na Google Play</Button>
        </div>
        <div className="t-small" style={{ color: 'var(--text-3)', textAlign: 'center', fontSize: 11 }}>
          Placeholder — zamijenit će se finalnom „Ocijenite nas" stranicom (ocjenite_nas).</div>
      </div>
    </Sheet>
  );
}

// ── Settings (Postavke) ───────────────────────────────────────
function SettingsScreen({ theme, setTheme, currency, setCurrency, notif, setNotif, onLogout }) {
  const [sheet, setSheet] = useSet(null);
  const [first, setFirst] = useSet(HIFA.user.firstName);
  const [last, setLast] = useSet(HIFA.user.lastName);
  const [email, setEmail] = useSet(HIFA.user.email);
  // draft fields
  const [dFirst, setDFirst] = useSet(first);
  const [dLast, setDLast] = useSet(last);
  const [dEmail, setDEmail] = useSet('');
  const [pw, setPw] = useSet({ cur: '', nw: '', cf: '' });

  const initials = (first[0] || '') + (last[0] || '');
  const openProfile = () => { setDFirst(first); setDLast(last); setSheet('profile'); };
  const openEmail = () => { setDEmail(''); setSheet('email'); };
  const openPw = () => { setPw({ cur: '', nw: '', cf: '' }); setSheet('password'); };

  return (
    <div style={{ padding: '16px 18px 24px', display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--hifa-gold-grad)', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 20, color: 'var(--on-gold)' }}>
          {initials.toUpperCase()}</div>
        <div>
          <div className="t-h3" style={{ color: 'var(--text)' }}>{first} {last}</div>
          <div className="t-small" style={{ color: 'var(--text-3)' }}>{email}</div>
        </div>
      </div>

      <Group>
        <Row icon="palette" title="Tema" trailing={
          <div style={{ display: 'flex', background: 'var(--surface-2)', borderRadius: 999, padding: 3, gap: 2 }}>
            {[{ k: 'dark', i: 'moon' }, { k: 'light', i: 'sun' }].map(o => (
              <Pressable key={o.k} onClick={() => setTheme(o.k)} style={{ width: 34, height: 28, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: theme === o.k ? 'var(--hifa-gold)' : 'transparent' }}>
                <Icon name={o.i} size={15} color={theme === o.k ? 'var(--on-gold)' : 'var(--text-3)'} />
              </Pressable>
            ))}
          </div>} />
        <Row icon="coins" title="Valuta" trailing={
          <div style={{ display: 'flex', background: 'var(--surface-2)', borderRadius: 999, padding: 3, gap: 2 }}>
            {['KM', 'EUR'].map(c => (
              <Pressable key={c} onClick={() => setCurrency(c)} style={{ padding: '5px 12px', borderRadius: 999,
                background: currency === c ? 'var(--hifa-gold)' : 'transparent' }}>
                <span className="t-label" style={{ fontSize: 11, color: currency === c ? 'var(--on-gold)' : 'var(--text-3)' }}>{c}</span>
              </Pressable>
            ))}
          </div>} last />
      </Group>

      <Group>
        <Row icon="bell" title="Notifikacije" trailing={<Toggle on={notif} onChange={setNotif} />} />
        <Row icon="user" title="Profil korisnika" detail={`${first} ${last}`} onClick={openProfile} />
        <Row icon="mail" title="E-mail adresa" detail={email} onClick={openEmail} />
        <Row icon="lock" title="Lozinka" detail="Promijeni" onClick={openPw} last />
      </Group>

      <Group>
        <Row icon="file-text" title="Uslovi korištenja" onClick={() => setSheet('terms')} />
        <Row icon="circle-help" title="Često postavljana pitanja"
          trailing={<Icon name="external-link" size={17} color="var(--text-3)" />}
          onClick={() => window.open(FAQ_URL, '_blank')} />
        <Row icon="star" title="Ocijenite nas" onClick={() => setSheet('rate')} last />
      </Group>

      <Group>
        <Row icon="trash-2" title="Deaktiviraj račun" danger onClick={() => setSheet('deactivate')} />
        <Row icon="log-out" title="Odjava" danger onClick={onLogout} trailing={null} last />
      </Group>

      <div style={{ textAlign: 'center', marginTop: 4 }}>
        <div className="t-small" style={{ color: 'var(--text-3)' }}>HIFA OIL Loyalty · verzija 2.0.0</div>
      </div>

      {/* ── Profil korisnika ── */}
      <Sheet open={sheet === 'profile'} onClose={() => setSheet(null)} title="Profil korisnika">
        <SheetForm>
          <Field label="Ime" value={dFirst} onChange={setDFirst} icon="user" />
          <Field label="Prezime" value={dLast} onChange={setDLast} icon="user" />
          <Button full size="lg" onClick={() => { setFirst(dFirst.trim() || first); setLast(dLast.trim() || last); setSheet(null); }}>Sačuvaj izmjene</Button>
        </SheetForm>
      </Sheet>

      {/* ── E-mail adresa ── */}
      <Sheet open={sheet === 'email'} onClose={() => setSheet(null)} title="Promjena e-maila">
        <SheetForm>
          <div style={{ padding: '12px 14px', borderRadius: 'var(--r-input)', background: 'var(--surface-2)' }}>
            <div className="t-label" style={{ color: 'var(--text-3)', marginBottom: 4 }}>Trenutni e-mail</div>
            <div className="t-body" style={{ color: 'var(--text)', fontWeight: 600 }}>{email}</div>
          </div>
          <Field label="Novi e-mail" value={dEmail} onChange={setDEmail} icon="mail" type="email" />
          <p className="t-small" style={{ color: 'var(--text-3)', margin: 0 }}>Na novu adresu poslat ćemo link za potvrdu.</p>
          <Button full size="lg" onClick={() => { if (dEmail.includes('@')) setEmail(dEmail.trim()); setSheet(null); }}>Potvrdi novi e-mail</Button>
        </SheetForm>
      </Sheet>

      {/* ── Lozinka ── */}
      <Sheet open={sheet === 'password'} onClose={() => setSheet(null)} title="Promjena lozinke">
        <SheetForm>
          <Field label="Trenutna lozinka" value={pw.cur} onChange={v => setPw({ ...pw, cur: v })} type="password" icon="lock" />
          <Field label="Nova lozinka" value={pw.nw} onChange={v => setPw({ ...pw, nw: v })} type="password" icon="lock-keyhole" />
          <Field label="Potvrdi novu lozinku" value={pw.cf} onChange={v => setPw({ ...pw, cf: v })} type="password" icon="lock-keyhole" />
          <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: -2 }}>
            <Icon name={pw.nw && pw.nw === pw.cf ? 'circle-check' : 'info'} size={15}
              color={pw.nw && pw.nw === pw.cf ? 'var(--success)' : 'var(--text-3)'} />
            <span className="t-small" style={{ color: pw.nw && pw.nw === pw.cf ? 'var(--success)' : 'var(--text-3)' }}>
              {pw.nw && pw.nw === pw.cf ? 'Lozinke se podudaraju' : 'Najmanje 8 karaktera'}</span>
          </div>
          <Button full size="lg" onClick={() => setSheet(null)}>Promijeni lozinku</Button>
        </SheetForm>
      </Sheet>

      {/* ── Uslovi korištenja ── */}
      <Sheet open={sheet === 'terms'} onClose={() => setSheet(null)} title="Uslovi korištenja">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {TERMS.map(([h, b], i) => (
            <div key={i}>
              <div className="t-h3" style={{ color: 'var(--text)', fontSize: 15, marginBottom: 5 }}>{h}</div>
              <p className="t-small" style={{ color: 'var(--text-2)', margin: 0, lineHeight: 1.55 }}>{b}</p>
            </div>
          ))}
          <div className="t-small" style={{ color: 'var(--text-3)', fontSize: 11 }}>Posljednje ažuriranje: juni 2026. · Placeholder tekst.</div>
        </div>
      </Sheet>

      {/* ── Ocijenite nas ── */}
      <RateSheet open={sheet === 'rate'} onClose={() => setSheet(null)} />

      {/* ── Deaktiviraj račun (potvrda) ── */}
      <Sheet open={sheet === 'deactivate'} onClose={() => setSheet(null)} title={null}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, paddingTop: 4 }}>
          <div style={{ width: 62, height: 62, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: 'color-mix(in srgb, var(--danger) 16%, transparent)' }}>
            <Icon name="triangle-alert" size={30} color="var(--danger)" />
          </div>
          <h3 className="t-h2" style={{ color: 'var(--text)', margin: 0, textAlign: 'center' }}>Deaktivirati račun?</h3>
          <p className="t-body" style={{ color: 'var(--text-2)', textAlign: 'center', margin: 0, maxWidth: 290 }}>
            Vaš ISOMAX Loyalty račun će biti deaktiviran, a vaši bodovi neće biti dostupni. Ova radnja se ne može poništiti.</p>
          <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
            <Button full size="lg" variant="danger" onClick={() => { setSheet(null); onLogout(); }}>Da, deaktiviraj račun</Button>
            <Button full variant="dark" onClick={() => setSheet(null)}>Odustani</Button>
          </div>
        </div>
      </Sheet>
    </div>
  );
}

Object.assign(window, { SettingsScreen });
