/* AIWine — the five settings screens behind the You tab.
   Each opens as a full sheet. Preferences and Notifications live on the device
   (and in the member's record when signed in); Delivery & payment uses the
   website's saved address so checkout is the same on both surfaces. */
const SETTINGS_KEY = 'aiwine:prefs';
function readPrefs() {
  const d = { minPrice: 15, maxPrice: 80, avoid: [], noSweet: false, organicFirst: false, units: 'NZD',
    notify: { window: true, orders: true, releases: false, marketing: false } };
  try { return Object.assign(d, JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}')); } catch (e) { return d; }
}
function writePrefs(p) { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(p)); } catch (e) {} return p; }

function SettingsSheet({ open, onClose, title, sub, children }) {
  return (
    <Sheet open={open} onClose={onClose} height="90%">
      <div className="aw-scroll" style={{ position: 'absolute', inset: 0, overflowY: 'auto', padding: '34px 22px 30px' }}>
        <Eyebrow>Settings</Eyebrow>
        <div style={{ ...S.serif, fontSize: 31, lineHeight: 1.06, marginTop: 10, color: 'var(--ink)' }}>{title}</div>
        {sub && <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 12 }}>{sub}</div>}
        <div style={{ marginTop: 24 }}>{children}</div>
      </div>
    </Sheet>
  );
}

function Toggle({ on, onChange, label, note }) {
  return (
    <div onClick={() => onChange(!on)} style={{ display: 'flex', gap: 14, alignItems: 'flex-start', padding: '15px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
      <div style={{ flex: 1 }}>
        <div style={{ ...S.serif, fontSize: 19, color: 'var(--ink)' }}>{label}</div>
        {note && <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 4, lineHeight: 1.45 }}>{note}</div>}
      </div>
      <div style={{ width: 46, height: 27, borderRadius: 100, flex: 'none', marginTop: 2, background: on ? 'var(--claret)' : 'var(--line)', position: 'relative', transition: 'background .18s' }}>
        <div style={{ position: 'absolute', top: 3, left: on ? 22 : 3, width: 21, height: 21, borderRadius: '50%', background: 'var(--bg)', transition: 'left .18s', boxShadow: '0 1px 3px rgba(27,20,16,.3)' }} />
      </div>
    </div>
  );
}

const FIELD_L = { ...S.mono, fontSize: 9, color: 'var(--muted)', marginBottom: 6 };
const FIELD_I = { width: '100%', boxSizing: 'border-box', border: '1px solid var(--line)', borderRadius: 12, padding: '13px 14px', ...S.sans, fontSize: 14.5, background: 'var(--card)', color: 'var(--ink)', outline: 'none' };

/* ---------- 1 · Preferences ---------- */
function PrefsScreen({ open, onClose, onSaved }) {
  const [p, setP] = React.useState(readPrefs);
  React.useEffect(() => { if (open) setP(readPrefs()); }, [open]);
  const varieties = [...new Set(AIW.wines.map(w => w.variety).filter(Boolean))].sort();
  const toggleAvoid = v => setP(x => ({ ...x, avoid: x.avoid.includes(v) ? x.avoid.filter(y => y !== v) : [...x.avoid, v] }));
  const save = () => { writePrefs(p); onSaved && onSaved(); onClose(); };

  return (
    <SettingsSheet open={open} onClose={onClose} title="Preferences"
      sub="The things I should never have to guess. These filter what I recommend — they don’t hide anything from search.">
      <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)' }}>What you usually spend</div>
      <div style={{ ...S.serif, fontSize: 26, color: 'var(--ink)', marginTop: 8 }}>${p.minPrice} – ${p.maxPrice}</div>
      <div style={{ display: 'flex', gap: 14, marginTop: 14 }}>
        <label style={{ flex: 1 }}>
          <div style={FIELD_L}>Lowest</div>
          <input type="range" min="10" max="150" step="5" value={p.minPrice} onChange={e => setP(x => ({ ...x, minPrice: Math.min(+e.target.value, x.maxPrice - 5) }))} style={{ width: '100%', accentColor: 'var(--claret)' }} />
        </label>
        <label style={{ flex: 1 }}>
          <div style={FIELD_L}>Highest</div>
          <input type="range" min="15" max="250" step="5" value={p.maxPrice} onChange={e => setP(x => ({ ...x, maxPrice: Math.max(+e.target.value, x.minPrice + 5) }))} style={{ width: '100%', accentColor: 'var(--claret)' }} />
        </label>
      </div>
      <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 10, lineHeight: 1.5 }}>I’ll still show something exceptional above this — I’ll just tell you why it’s worth the stretch.</div>

      <div style={{ height: 28 }} />
      <div style={{ ...S.mono, fontSize: 9, color: 'var(--muted)', marginBottom: 12 }}>Never recommend</div>
      {varieties.length ? (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
          {varieties.map(v => <Chip key={v} active={p.avoid.includes(v)} onClick={() => toggleAvoid(v)}>{v}</Chip>)}
        </div>
      ) : <div style={{ ...S.sans, fontSize: 13, color: 'var(--muted)' }}>Grape varieties appear here once the library loads.</div>}
      <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 10, lineHeight: 1.5 }}>Tap anything you’d rather never be offered. Better than rating wines badly to make me stop.</div>

      <div style={{ height: 20 }} />
      <Toggle on={p.noSweet} onChange={v => setP(x => ({ ...x, noSweet: v }))} label="Nothing sweet" note="Skip off-dry and dessert styles entirely." />
      <Toggle on={p.organicFirst} onChange={v => setP(x => ({ ...x, organicFirst: v }))} label="Favour organic & biodynamic" note="When two wines are close, I’ll lead with the organic one." />

      <div style={{ marginTop: 26 }}><Btn full onClick={save}>Save preferences</Btn></div>
    </SettingsSheet>
  );
}

/* ---------- 2 · Delivery & payment ---------- */
function DeliveryScreen({ open, onClose, onSaved }) {
  const blank = { name: '', line1: '', line2: '', suburb: '', city: '', postcode: '', phone: '', instructions: '', pickup: false };
  const [a, setA] = React.useState(blank);
  const [saved, setSaved] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    setSaved(false);
    try { setA(Object.assign({}, blank, (window.AIAccount && AIAccount.getAddress && AIAccount.getAddress()) || {})); } catch (e) { setA(blank); }
  }, [open]);
  const set = k => e => setA(x => ({ ...x, [k]: e.target.value }));
  const F = ({ k, label, ...rest }) => (
    <div style={{ marginBottom: 13 }}><div style={FIELD_L}>{label}</div><input value={a[k] || ''} onChange={set(k)} style={FIELD_I} {...rest} /></div>
  );
  const save = () => {
    try { window.AIAccount && AIAccount.saveAddress && AIAccount.saveAddress(a); } catch (e) {}
    setSaved(true); onSaved && onSaved();
    setTimeout(onClose, 900);
  };

  return (
    <SettingsSheet open={open} onClose={onClose} title="Delivery & payment"
      sub="One address for the app and the website — whichever you check out from.">
      <F k="name" label="Name" autoComplete="name" />
      <F k="line1" label="Street address" autoComplete="address-line1" />
      <F k="line2" label="Apartment, unit (optional)" autoComplete="address-line2" />
      <div style={{ display: 'flex', gap: 12 }}>
        <div style={{ flex: 1 }}><F k="suburb" label="Suburb" /></div>
        <div style={{ flex: 1 }}><F k="city" label="City" autoComplete="address-level2" /></div>
      </div>
      <div style={{ display: 'flex', gap: 12 }}>
        <div style={{ flex: 1 }}><F k="postcode" label="Postcode" inputMode="numeric" autoComplete="postal-code" /></div>
        <div style={{ flex: 1 }}><F k="phone" label="Phone" inputMode="tel" autoComplete="tel" /></div>
      </div>
      <F k="instructions" label="Delivery notes (optional)" placeholder="e.g. leave with the neighbour" />
      <Toggle on={a.pickup} onChange={v => setA(x => ({ ...x, pickup: v }))} label="Prefer cellar-door pickup" note="Where the winery offers it, I’ll default to pickup instead of courier." />

      <div style={{ marginTop: 24, borderRadius: 16, border: '1px solid var(--line)', background: 'var(--bg-alt)', padding: 18 }}>
        <Eyebrow>Payment</Eyebrow>
        <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 10 }}>
          Card details are never stored by AIWine. You enter them once at checkout with our payment provider, who keeps them securely for next time.
        </div>
        <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 10 }}>Someone must be 18 or over to receive a wine delivery.</div>
      </div>

      <div style={{ marginTop: 22 }}><Btn full onClick={save}>{saved ? 'Saved ✓' : 'Save address'}</Btn></div>
    </SettingsSheet>
  );
}

/* ---------- 3 · Notifications ---------- */
function NotifyScreen({ open, onClose, onSaved }) {
  const [p, setP] = React.useState(readPrefs);
  const [perm, setPerm] = React.useState(typeof Notification !== 'undefined' ? Notification.permission : 'unsupported');
  React.useEffect(() => { if (open) setP(readPrefs()); }, [open]);
  const set = (k, v) => { const next = { ...p, notify: { ...p.notify, [k]: v } }; setP(next); writePrefs(next); onSaved && onSaved(); };
  async function ask() {
    if (typeof Notification === 'undefined') return;
    try { setPerm(await Notification.requestPermission()); } catch (e) {}
  }

  return (
    <SettingsSheet open={open} onClose={onClose} title="Notifications"
      sub="Three things worth interrupting you for. Nothing else — I’d rather you kept these on.">
      {perm !== 'granted' && perm !== 'unsupported' && (
        <div style={{ marginBottom: 20, borderRadius: 16, border: '1px solid var(--line)', background: 'var(--bg-alt)', padding: 18 }}>
          <div style={{ ...S.serif, fontSize: 20, color: 'var(--ink)' }}>{perm === 'denied' ? 'Notifications are blocked' : 'Allow notifications?'}</div>
          <div style={{ ...S.sans, fontSize: 13, color: 'var(--ink-soft)', marginTop: 8, lineHeight: 1.5 }}>
            {perm === 'denied'
              ? 'Your phone is blocking them for AIWine. Turn them back on in your device settings, then return here.'
              : 'Your choices below only take effect once your phone allows them.'}
          </div>
          {perm === 'default' && <div style={{ marginTop: 14 }}><Btn small onClick={ask}>Allow notifications</Btn></div>}
        </div>
      )}
      <Toggle on={p.notify.window} onChange={v => set('window', v)} label="A wine enters its window" note="The one alert worth having — a bottle you own is ready to drink." />
      <Toggle on={p.notify.orders} onChange={v => set('orders', v)} label="Order updates" note="Confirmations and when a winery ships your wine." />
      <Toggle on={p.notify.releases} onChange={v => set('releases', v)} label="New releases from wineries you own" note="Only wineries already in your cellar. Off by default." />
      <Toggle on={p.notify.marketing} onChange={v => set('marketing', v)} label="Occasional emails from AIWine" note="Wine writing and offers. Never more than monthly." />
      <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 18, lineHeight: 1.5 }}>Saved as you tap. Order and delivery messages about a purchase you’ve made are sent regardless — they’re part of the sale.</div>
    </SettingsSheet>
  );
}

/* ---------- 4 · Privacy ---------- */
function PrivacyScreen({ open, onClose }) {
  const [confirm, setConfirm] = React.useState(false);
  const [done, setDone] = React.useState('');
  React.useEffect(() => { if (open) { setConfirm(false); setDone(''); } }, [open]);

  function exportData() {
    const bundle = {
      exported: new Date().toISOString(),
      account: AIW.email() || 'not signed in',
      tier: AIW.planKey(),
      tasteProfile: AIW.profile,
      cellar: AIW.cellar(),
      ownBottles: AIW.customs(),
      tastings: AIW.history(),
      cart: AIW.cart(),
      preferences: readPrefs()
    };
    const blob = new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'aiwine-my-data.json';
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(a.href), 4000);
    setDone('Your data has downloaded as a file.');
  }

  return (
    <SettingsSheet open={open} onClose={onClose} title="Privacy"
      sub="What we hold, why, and how to take it back. Plain language, no small print.">
      {[['What we keep', 'Your account email, the wines in your cellar, what you’ve rated, your taste profile, and your orders. That is all of it.'],
        ['Why', 'To answer “what should I open tonight” properly. A recommendation engine with no memory is just a shop.'],
        ['Who sees it', 'AIWine staff, for support. A winery sees only what it needs to ship your order — your name, address, and what you bought. Never your cellar or your taste profile.'],
        ['What we never do', 'We don’t sell your data, and we don’t hold your card — our payment provider does.']].map(([t, d]) => (
        <div key={t} style={{ padding: '16px 0', borderTop: '1px solid var(--line-soft)' }}>
          <div style={{ ...S.serif, fontSize: 20, color: 'var(--ink)' }}>{t}</div>
          <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 6 }}>{d}</div>
        </div>
      ))}

      <div style={{ height: 22 }} />
      <div style={{ borderRadius: 16, border: '1px solid var(--line)', background: 'var(--card)', padding: 18 }}>
        <Eyebrow>Your rights</Eyebrow>
        <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 10 }}>
          Under the New Zealand Privacy Act you can ask for a copy of everything we hold about you, and ask us to correct or delete it.
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap' }}>
          <Btn small kind="ghost" onClick={exportData}>Download my data</Btn>
          <Btn small kind="ghost" onClick={() => setConfirm(true)}>Delete my account</Btn>
        </div>
        {done && <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--green)', marginTop: 12 }}>{done}</div>}
      </div>

      {confirm && (
        <div style={{ marginTop: 18, borderRadius: 16, border: '1px solid var(--claret)', padding: 18 }}>
          <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)' }}>Delete everything?</div>
          <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 8 }}>
            Your cellar, tastings and taste profile go permanently. Orders already placed are kept — we’re required to hold sales records for seven years.
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap' }}>
            <Btn small onClick={() => { window.location.href = 'mailto:privacy@aiwine.co.nz?subject=' + encodeURIComponent('Delete my AIWine account') + '&body=' + encodeURIComponent('Please delete my AIWine account and all associated data.\n\nAccount: ' + (AIW.email() || '(not signed in)')); setDone('Your request has been started in your email app. We action deletions within 5 working days.'); setConfirm(false); }}>Request deletion</Btn>
            <Btn small kind="ghost" onClick={() => setConfirm(false)}>Keep my account</Btn>
          </div>
        </div>
      )}

      <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 20, lineHeight: 1.5 }}>Questions? <span style={{ color: 'var(--claret)' }}>privacy@aiwine.co.nz</span></div>
    </SettingsSheet>
  );
}

/* ---------- 5 · Help ---------- */
const FAQ = [
  ['Why can’t it scan my imported bottle?', 'Scanning recognises New Zealand wines published on AIWine by their winery. Anything else — an import, a gift, an old vintage — you add to your cellar by hand in about fifteen seconds, and it behaves exactly like a library wine from then on.'],
  ['How does the match score work?', 'Your taste profile has four axes: weight, savouriness, structure and oak. Every wine is placed on the same axes, and the score is how close the two sit. Rate a wine and your profile moves — so the same bottle can score differently next month.'],
  ['Why is delivery different for each wine?', 'Because each winery sets its own rules and ships its own carton. Free delivery, minimum orders and case sizes are theirs, not ours — you’ll see that winery’s rules before you commit.'],
  ['What does membership actually get me?', 'Unlimited scanning and 10% off every bottle, for $9 a month. Your cellar, taste profile and asking me anything are free and stay free. It pays for itself at about $90 of wine a month.'],
  ['Is my cellar backed up?', 'Once you sign in, yes — your cellar, tastings and cart live on your account and follow you to any device. Signed out, they’re on this phone only.'],
  ['Can I buy a wine that’s sold out?', 'Not until the winery restocks. Ask me and I’ll find the closest thing that is available.']
];

function HelpScreen({ open, onClose }) {
  const [openQ, setOpenQ] = React.useState(null);
  return (
    <SettingsSheet open={open} onClose={onClose} title="Help"
      sub="The questions people actually ask. If yours isn’t here, just ask me in the app — I answer that too.">
      {FAQ.map(([q, a], i) => (
        <div key={i} onClick={() => setOpenQ(openQ === i ? null : i)} style={{ padding: '16px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
            <div style={{ ...S.serif, fontSize: 19, color: 'var(--ink)', flex: 1, lineHeight: 1.25 }}>{q}</div>
            <div style={{ ...S.sans, fontSize: 15, color: 'var(--claret)', flex: 'none' }}>{openQ === i ? '−' : '+'}</div>
          </div>
          {openQ === i && <div style={{ ...S.sans, fontSize: 13.5, lineHeight: 1.6, color: 'var(--ink-soft)', marginTop: 10 }}>{a}</div>}
        </div>
      ))}

      <div style={{ height: 24 }} />
      <div style={{ borderRadius: 16, border: '1px solid var(--line)', background: 'var(--card)', padding: 18 }}>
        <Eyebrow>Still stuck</Eyebrow>
        <div style={{ ...S.serif, fontSize: 21, color: 'var(--ink)', marginTop: 8 }}>Talk to a person</div>
        <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 8 }}>We’re a small team in Martinborough and we answer our own email, usually within a day.</div>
        <div style={{ marginTop: 14 }}><Btn small kind="ghost" onClick={() => { window.location.href = 'mailto:hello@aiwine.co.nz?subject=' + encodeURIComponent('AIWine app — help'); }}>Email us</Btn></div>
      </div>

      <div style={{ marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
        <Eyebrow>Drinking well</Eyebrow>
        <div style={{ ...S.sans, fontSize: 13, lineHeight: 1.6, color: 'var(--ink-soft)', marginTop: 10 }}>
          You must be 18 or over to buy wine in New Zealand, and someone 18 or over must be there to receive it. AIWine is about drinking better, not more — if alcohol is causing you trouble, <span style={{ color: 'var(--claret)' }}>alcoholdrughelp.org.nz</span> or 0800 787 797.
        </div>
      </div>

      <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--faint)', textAlign: 'center', marginTop: 26 }}>AIWine · Martinborough, Aotearoa · Terms &amp; privacy at aiwine.co.nz</div>
    </SettingsSheet>
  );
}

Object.assign(window, { readPrefs, writePrefs, SettingsSheet, Toggle, PrefsScreen, DeliveryScreen, NotifyScreen, PrivacyScreen, HelpScreen });
