// modals.jsx — Entry, Project, Config (types/currencies/people), Data (export/import)
const { useState: useS2, useEffect: useE2 } = React;

/* =========================================================
   ENTRY MODAL — add / edit a ledger entry
   ========================================================= */
function EntryModal({ project, entry, defaultOwner, onClose, toast }) {
  const S = Store.get();
  const editing = !!entry;
  const [f, setF] = useS2(() => entry ? { ...entry } : {
    name: '', value: '', currencyId: 'thb', typeId: S.types[0]?.id,
    owner: defaultOwner || S.owners[0]?.id, flow: 'spent', date: new Date().toISOString().slice(0,10), note: '',
  });
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));

  function save() {
    if (!f.name.trim()) { toast('Give it a name 🎀'); return; }
    const payload = { ...f, value: f.value === '' || f.value == null ? null : Number(f.value) };
    if (editing) Store.updateEntry(project.id, entry.id, payload);
    else Store.addEntry(project.id, payload);
    toast(editing ? 'Saved ✨' : 'Added ✨');
    onClose();
  }
  function del() { Store.deleteEntry(project.id, entry.id); toast('Deleted'); onClose(); }

  const flows = [['spent','Spent','chip-spent'],['have','Have','chip-have'],['received','Got','chip-recv']];

  return (
    <Modal title={editing ? 'Edit entry' : 'New entry'} onClose={onClose}
      icon={<div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 12 }}><Icon name="wallet" size={19} color="#fff"/></div>}>
      <div className="field">
        <label>What is it?</label>
        <input className="input" autoFocus value={f.name} placeholder="e.g. Ramen dinner, Hotel deposit…"
          onChange={e => set('name', e.target.value)} onKeyDown={e => e.key==='Enter' && save()} />
      </div>

      <div className="field">
        <label>Kind</label>
        <div className="seg">
          {flows.map(([id,label]) => (
            <button key={id} className={f.flow===id?'on':''} onClick={() => set('flow', id)} type="button">{label}</button>
          ))}
        </div>
      </div>

      <div className="row">
        <div className="field" style={{ flex: 1.3 }}>
          <label>Value <span className="faint">(leave blank for a note)</span></label>
          <input className="input" type="number" inputMode="decimal" value={f.value ?? ''} placeholder="0"
            onChange={e => set('value', e.target.value)} />
        </div>
        <div className="field">
          <label>Currency</label>
          <select className="select" value={f.currencyId ?? ''} onChange={e => set('currencyId', e.target.value || null)}>
            <option value="">— none —</option>
            {S.currencies.map(c => <option key={c.id} value={c.id}>{c.symbol} {c.code}</option>)}
          </select>
        </div>
      </div>

      <div className="field">
        <label>Type</label>
        <div className="pick-grid">
          {S.types.map(t => (
            <button key={t.id} type="button" className={`pick ${f.typeId===t.id?'on':''}`} onClick={() => set('typeId', t.id)}>
              <IconBadge name={t.icon} color={t.color} size={34} />
              <span>{t.name}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="row">
        <div className="field">
          <label>Who paid / has it?</label>
          <div className="seg">
            {S.owners.map(o => (
              <button key={o.id} className={f.owner===o.id?'on':''} onClick={() => set('owner', o.id)} type="button">
                <Avatar owner={o} size={18} /> {o.name}
              </button>
            ))}
          </div>
        </div>
        <div className="field">
          <label>Date</label>
          <input className="input" type="date" value={f.date} onChange={e => set('date', e.target.value)} />
        </div>
      </div>

      <div className="field">
        <label>Note <span className="faint">(optional)</span></label>
        <textarea className="textarea" value={f.note} placeholder="anything to remember about this…" onChange={e => set('note', e.target.value)} />
      </div>

      <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
        {editing && <button className="btn btn-ghost" onClick={del} style={{ color: '#E06363' }}>Delete</button>}
        <div className="spacer" />
        <button className="btn btn-soft" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={save}>{editing ? 'Save' : 'Add entry'}</button>
      </div>
    </Modal>
  );
}

/* =========================================================
   PROJECT MODAL
   ========================================================= */
const EMOJIS = ['🎀','🪙','🗼','🏠','✈️','🍰','🌸','💝','🧸','🌷','☕','🎮','🐰','🦊','🍙','💸'];
function ProjectModal({ project, onClose, toast }) {
  const editing = !!project;
  const [name, setName] = useS2(project?.name || '');
  const [emoji, setEmoji] = useS2(project?.emoji || '🎀');
  function save() {
    if (!name.trim()) { toast('Name your page 🌸'); return; }
    if (editing) Store.updateProject(project.id, { name, emoji });
    else Store.addProject({ name, emoji });
    toast(editing ? 'Saved ✨' : 'New page created ✨');
    onClose();
  }
  return (
    <Modal title={editing ? 'Edit page' : 'New page'} onClose={onClose}
      icon={<div className="proj-emoji" style={{ width: 36, height: 36 }}>{emoji}</div>}>
      <div className="field">
        <label>Page name</label>
        <input className="input" autoFocus value={name} placeholder="e.g. Japan Trip, Coin Game…"
          onChange={e => setName(e.target.value)} onKeyDown={e => e.key==='Enter' && save()} />
      </div>
      <div className="field">
        <label>Icon</label>
        <div className="swatch-row" style={{ gap: 6 }}>
          {EMOJIS.map(e => (
            <button key={e} type="button" onClick={() => setEmoji(e)}
              style={{ width: 40, height: 40, borderRadius: 13, fontSize: 19, background: emoji===e?'var(--accent-wash)':'var(--surface-soft)',
                border: emoji===e?'1.5px solid var(--accent)':'1.5px solid var(--line)' }}>{e}</button>
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
        {editing && <button className="btn btn-ghost" style={{ color: '#E06363' }}
          onClick={() => { if (confirm('Delete this page and all its entries?')) { Store.deleteProject(project.id); toast('Page deleted'); onClose(); } }}>Delete page</button>}
        <div className="spacer" />
        <button className="btn btn-soft" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={save}>{editing ? 'Save' : 'Create'}</button>
      </div>
    </Modal>
  );
}

/* =========================================================
   CONFIG MODAL — types · currencies · people
   ========================================================= */
function ConfigModal({ onClose, toast }) {
  const S = useStore().get();
  const [tab, setTab] = useS2('types');
  const [editT, setEditT] = useS2(null);   // type being edited (obj or 'new')
  const [editC, setEditC] = useS2(null);   // currency being edited

  return (
    <Modal wide title="Config" onClose={onClose}
      icon={<div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 12, background: 'linear-gradient(160deg,var(--lav),var(--lav-deep))' }}>
        <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4"/></svg></div>}>
      <div className="tabs" style={{ marginBottom: 18, width: 'fit-content' }}>
        {[['types','Types'],['currencies','Currencies'],['people','People']].map(([id,label]) => (
          <button key={id} className={`tab ${tab===id?'active':''}`} onClick={() => setTab(id)}>{label}</button>
        ))}
      </div>

      {tab === 'types' && (editT ? (
        <TypeEditor type={editT==='new'?null:editT} onDone={() => setEditT(null)} toast={toast} />
      ) : (
        <div>
          {S.types.map(t => (
            <div className="cfg-row" key={t.id}>
              <IconBadge name={t.icon} color={t.color} size={38} />
              <div style={{ flex: 1, fontFamily: 'var(--font-ui)', fontWeight: 600 }}>{t.name}</div>
              <div className="cfg-actions">
                <button className="icn-btn" onClick={() => setEditT(t)} title="Edit"><EditIco/></button>
                <button className="icn-btn danger" onClick={() => { if (S.types.length<=1) return toast('Keep at least one type'); Store.deleteType(t.id); }} title="Delete"><TrashIco/></button>
              </div>
            </div>
          ))}
          <button className="btn btn-soft" style={{ marginTop: 8, width: '100%' }} onClick={() => setEditT('new')}>＋ Add type</button>
        </div>
      ))}

      {tab === 'currencies' && (editC ? (
        <CurrencyEditor cur={editC==='new'?null:editC} onDone={() => setEditC(null)} toast={toast} />
      ) : (
        <div>
          <p className="muted" style={{ fontSize: 13, margin: '0 4px 14px', lineHeight: 1.5 }}>
            <b>Rate → ฿THB</b> lets the dashboard total mixed currencies. e.g. 1 Coin = 10 ฿, 1 ¥ = 0.24 ฿.
          </p>
          {S.currencies.map(c => (
            <div className="cfg-row" key={c.id}>
              <div style={{ width: 38, height: 38, borderRadius: 12, display: 'grid', placeItems: 'center', background: tint(c.color,0.16), color: c.color, fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 18 }}>{c.symbol}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-ui)', fontWeight: 600 }}>{c.code} {c.base && <span className="chip chip-have" style={{ marginLeft: 4 }}>base</span>} {c.fun && <span className="chip chip-recv" style={{ marginLeft: 4 }}>fun</span>}</div>
                <div className="faint" style={{ fontSize: 12, fontWeight: 600 }}>1 {c.code} = {c.rateToBase} ฿</div>
              </div>
              <div className="cfg-actions">
                <button className="icn-btn" onClick={() => setEditC(c)} title="Edit"><EditIco/></button>
                {!c.base && <button className="icn-btn danger" onClick={() => Store.deleteCurrency(c.id)} title="Delete"><TrashIco/></button>}
              </div>
            </div>
          ))}
          <button className="btn btn-soft" style={{ marginTop: 8, width: '100%' }} onClick={() => setEditC('new')}>＋ Add currency</button>
        </div>
      ))}

      {tab === 'people' && (
        <div>
          {S.owners.map(o => (
            <div className="cfg-row" key={o.id} style={{ alignItems: 'flex-start', flexDirection: 'column', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%' }}>
                <Avatar owner={o} size={36} />
                <input className="input" value={o.name} onChange={e => Store.updateOwner(o.id, { name: e.target.value })} style={{ flex: 1 }} />
              </div>
              <ColorPicker value={o.color} onChange={c => Store.updateOwner(o.id, { color: c })} />
            </div>
          ))}
          <p className="muted" style={{ fontSize: 13, margin: '10px 4px 0' }}>The two of you 💕 Rename or recolor anytime.</p>
        </div>
      )}
    </Modal>
  );
}

function TypeEditor({ type, onDone, toast }) {
  const [f, setF] = useS2(() => type ? { ...type } : { name: '', icon: 'star', color: '#EC6F9E' });
  const set = (k,v) => setF(p => ({ ...p, [k]: v }));
  function save() {
    if (!f.name.trim()) return toast('Name the type');
    if (type) Store.updateType(type.id, f); else Store.addType(f);
    toast('Saved ✨'); onDone();
  }
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
        <IconBadge name={f.icon} color={f.color} size={56} radius={18} />
        <input className="input" autoFocus value={f.name} placeholder="Type name" onChange={e => set('name', e.target.value)} style={{ flex: 1 }} />
      </div>
      <div className="field"><label>Icon</label><IconPicker value={f.icon} onChange={v => set('icon', v)} /></div>
      <div className="field"><label>Color</label><ColorPicker value={f.color} onChange={v => set('color', v)} /></div>
      <div style={{ display: 'flex', gap: 10 }}>
        <button className="btn btn-soft" onClick={onDone}>Back</button>
        <div className="spacer" />
        <button className="btn btn-primary" onClick={save}>Save type</button>
      </div>
    </div>
  );
}

function CurrencyEditor({ cur, onDone, toast }) {
  const [f, setF] = useS2(() => cur ? { ...cur } : { code: '', symbol: '', color: '#5683C4', rateToBase: 1, fun: false });
  const set = (k,v) => setF(p => ({ ...p, [k]: v }));
  function save() {
    if (!f.code.trim()) return toast('Add a code (e.g. USD)');
    const payload = { ...f, rateToBase: Number(f.rateToBase) || 1 };
    if (cur) Store.updateCurrency(cur.id, payload); else Store.addCurrency(payload);
    toast('Saved ✨'); onDone();
  }
  return (
    <div>
      <div className="row">
        <div className="field"><label>Code</label><input className="input" autoFocus value={f.code} placeholder="USD" onChange={e => set('code', e.target.value)} /></div>
        <div className="field"><label>Symbol</label><input className="input" value={f.symbol} placeholder="$ or 🪙" onChange={e => set('symbol', e.target.value)} /></div>
      </div>
      <div className="field">
        <label>Rate → 1 unit = ? ฿THB</label>
        <input className="input" type="number" inputMode="decimal" value={f.rateToBase} onChange={e => set('rateToBase', e.target.value)} />
      </div>
      <div className="field"><label>Color</label><ColorPicker value={f.color} onChange={v => set('color', v)} /></div>
      <div className="field">
        <label>Fun currency? <span className="faint">(like play-money Coins)</span></label>
        <div className="seg" style={{ maxWidth: 220 }}>
          <button className={!f.fun?'on':''} onClick={() => set('fun', false)} type="button">Real</button>
          <button className={f.fun?'on':''} onClick={() => set('fun', true)} type="button">Fun 🪙</button>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <button className="btn btn-soft" onClick={onDone}>Back</button>
        <div className="spacer" />
        <button className="btn btn-primary" onClick={save}>Save currency</button>
      </div>
    </div>
  );
}

/* =========================================================
   DATA MODAL — export / import + cloud sync note
   ========================================================= */
function DataModal({ onClose, toast }) {
  const [mode, setMode] = useS2('sync');
  const [text, setText] = useS2('');
  function doExport() {
    const data = Store.exportJSON();
    const blob = new Blob([data], { type: 'application/json' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `our-little-ledger-${new Date().toISOString().slice(0,10)}.json`;
    a.click(); toast('Downloaded backup 💾');
  }
  async function copyData() { try { await navigator.clipboard.writeText(Store.exportJSON()); toast('Copied to clipboard 📋'); } catch { toast('Copy failed'); } }
  function doImport() {
    try { Store.importJSON(text); toast('Data loaded 💕'); onClose(); }
    catch (e) { toast('That doesn’t look like a ledger file'); }
  }
  return (
    <Modal title="Save & share" onClose={onClose}
      icon={<div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 12, background: 'linear-gradient(160deg,var(--mint),var(--mint-deep))' }}><Icon name="wallet" size={18} color="#fff"/></div>}>
      <div className="tabs" style={{ marginBottom: 18, width: 'fit-content' }}>
        {[['sync','Live sync ✨'],['share','How it works'],['backup','Backup / restore']].map(([id,l]) => (
          <button key={id} className={`tab ${mode===id?'active':''}`} onClick={() => setMode(id)}>{l}</button>
        ))}
      </div>

      {mode === 'sync' && <SyncPanel toast={toast} />}

      {mode !== 'sync' && (mode === 'share' ? (
        <div style={{ fontSize: 14, lineHeight: 1.6 }}>
          <div className="card-soft" style={{ marginBottom: 12 }}>
            <b style={{ fontFamily: 'var(--font-ui)' }}>✅ Right now</b>
            <p className="muted" style={{ margin: '6px 0 0' }}>Everything you add saves automatically on this device and stays here when you come back — even after a refresh.</p>
          </div>
          <div className="card-soft" style={{ marginBottom: 12 }}>
            <b style={{ fontFamily: 'var(--font-ui)' }}>💕 To both see the same live data</b>
            <p className="muted" style={{ margin: '6px 0 0' }}>Two free steps (ask Codex to review these when you’re ready):</p>
            <ol className="muted" style={{ margin: '8px 0 0', paddingLeft: 20 }}>
              <li>Host this on a free public link (Netlify / Vercel).</li>
              <li>Add a free shared database (Firebase) so View &amp; Mimi sync in real time.</li>
            </ol>
          </div>
          <div className="card-soft">
            <b style={{ fontFamily: 'var(--font-ui)' }}>📋 Quick sync today</b>
            <p className="muted" style={{ margin: '6px 0 0' }}>Use <b>Backup / restore</b> to copy your data and paste it on the other phone.</p>
          </div>
        </div>
      ) : (
        <div>
          <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
            <button className="btn btn-primary" onClick={doExport}>💾 Download backup</button>
            <button className="btn btn-ghost" onClick={copyData}>📋 Copy data</button>
          </div>
          <div className="field">
            <label>Restore — paste a backup here</label>
            <textarea className="textarea" style={{ minHeight: 120, fontFamily: 'ui-monospace, monospace', fontSize: 12 }}
              value={text} placeholder='{ "projects": [ … ] }' onChange={e => setText(e.target.value)} />
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn-ghost" style={{ color: '#E06363' }}
              onClick={() => { if (confirm('Reset everything back to the sample data?')) { Store.reset(); toast('Reset done'); onClose(); } }}>Reset to sample</button>
            <div className="spacer" />
            <button className="btn btn-primary" onClick={doImport} disabled={!text.trim()} style={{ opacity: text.trim()?1:.5 }}>Load data</button>
          </div>
        </div>
      ))}
    </Modal>
  );
}

/* =========================================================
   SYNC PANEL — set up free Firebase live sync between phones
   ========================================================= */
function SyncPanel({ toast }) {
  const cfg = window.Sync ? Sync.getConfig() : null;
  const [st, setSt] = useS2(window.Sync ? Sync.getStatus() : { status: 'off' });
  const [showForm, setShowForm] = useS2(!cfg);
  const [blob, setBlob] = useS2('');
  const [room, setRoom] = useS2(cfg?.room || 'view-and-mimi');

  useE2(() => window.Sync ? Sync.onStatus((status, detail) => setSt({ status, detail })) : undefined, []);

  function connect() {
    try {
      const firebase = Sync.parseFirebaseConfig(blob);
      if (!room.trim()) return toast('Pick a pair code');
      Sync.save({ firebase, room: room.trim().toLowerCase().replace(/\s+/g, '-') });
      toast('Connecting to your shared ledger… ✨');
      setShowForm(false);
    } catch (e) { toast(e.message || 'Could not read that config'); }
  }
  function disconnect() {
    if (confirm('Stop live sync on this device? Your data stays saved locally.')) { Sync.clear(); setShowForm(true); toast('Live sync turned off'); }
  }

  const dot = { off: '#B5A3AD', connecting: '#E0A93F', live: '#3FA277', error: '#E06363' }[st.status] || '#B5A3AD';
  const label = { off: 'Not connected', connecting: 'Connecting…', live: 'Live — synced 💕', error: 'Error: ' + (st.detail || '') }[st.status];

  return (
    <div style={{ fontSize: 14, lineHeight: 1.55 }}>
      {/* status banner */}
      <div className="card-soft" style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 14 }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: dot, boxShadow: `0 0 0 4px ${tint(dot, 0.18)}`, flexShrink: 0 }} />
        <div style={{ flex: 1, fontFamily: 'var(--font-ui)', fontWeight: 600 }}>{label}</div>
        {cfg && !showForm && <button className="btn btn-ghost btn-sm" onClick={disconnect} style={{ color: '#E06363' }}>Turn off</button>}
        {cfg && showForm && <button className="btn btn-soft btn-sm" onClick={() => setShowForm(false)}>Cancel</button>}
      </div>

      {!showForm ? (
        <div>
          <div className="card-soft" style={{ marginBottom: 12 }}>
            <b style={{ fontFamily: 'var(--font-ui)' }}>Pair code</b>
            <p className="muted" style={{ margin: '4px 0 0' }}>You &amp; Mimi share this code: <b style={{ color: 'var(--rose-deep)' }}>{cfg?.room}</b>. Anyone with the same Firebase config + pair code sees the same ledger.</p>
          </div>
          <p className="muted" style={{ fontSize: 13 }}>✨ Edits on either phone now appear on both, live. Want to reconnect to a different project? <button className="link-btn" onClick={() => setShowForm(true)} style={{ color: 'var(--rose)', fontWeight: 700 }}>Edit setup</button></p>
        </div>
      ) : (
        <div>
          <div className="card-soft" style={{ marginBottom: 14 }}>
            <b style={{ fontFamily: 'var(--font-ui)' }}>🔧 One-time setup (~10 min, free)</b>
            <ol className="muted" style={{ margin: '8px 0 0', paddingLeft: 20, display: 'flex', flexDirection: 'column', gap: 5 }}>
              <li>Go to <b>console.firebase.google.com</b> → <b>Add project</b> (any name).</li>
              <li>Build → <b>Firestore Database</b> → <b>Create</b> → choose <b>production mode</b>, then review restrictive rules before adding private data.</li>
              <li>Project settings ⚙️ → <b>Your apps</b> → <b>Web</b> (&lt;/&gt;) → register → copy the <b>firebaseConfig</b>.</li>
              <li>Paste it below. Send Mimi this same config + pair code.</li>
            </ol>
          </div>
          <div className="field">
            <label>Paste your firebaseConfig</label>
            <textarea className="textarea" style={{ minHeight: 130, fontFamily: 'ui-monospace, monospace', fontSize: 12 }}
              value={blob} placeholder={'const firebaseConfig = {\n  apiKey: "AIza…",\n  projectId: "our-ledger",\n  appId: "1:…"\n};'} onChange={e => setBlob(e.target.value)} />
          </div>
          <div className="field">
            <label>Pair code <span className="faint">(any shared word — both of you use the same)</span></label>
            <input className="input" value={room} onChange={e => setRoom(e.target.value)} placeholder="view-and-mimi" />
          </div>
          <button className="btn btn-primary" style={{ width: '100%' }} onClick={connect}>💕 Connect live sync</button>
          <p className="faint" style={{ fontSize: 11.5, marginTop: 10, lineHeight: 1.5 }}>Do not use test mode for private data. Ask Codex to review and test restrictive Firestore rules before connecting real ledger data.</p>
        </div>
      )}
    </div>
  );
}

/* small inline icons */
function EditIco() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9M16.5 3.5a2 2 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>; }
function TrashIco() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13"/></svg>; }

Object.assign(window, { EntryModal, ProjectModal, ConfigModal, DataModal });
