// piggy-bank.jsx — dedicated savings jars page for View & Mimi
const { useState: usePiggyState } = React;

const PIGGY_COLORS = ['#EC6F9E', '#C79BE0', '#5683C4', '#5BA88A', '#E0A93F', '#E0883F'];

function KittyProjectIcon({ size = 24 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none" aria-hidden="true">
      <path d="M8.5 19 11 7l10 6c2-.4 4-.4 6 0l10-6 2.5 12c2.1 2.5 3 5.4 3 8.4C42.5 37 34.4 42 24 42S5.5 37 5.5 27.4c0-3 1-5.9 3-8.4Z" fill="#FFFDFC" stroke="#574C51" strokeWidth="2.1" strokeLinejoin="round"/>
      <ellipse cx="18" cy="27" rx="1.65" ry="2.35" fill="#4E4549"/><ellipse cx="30" cy="27" rx="1.65" ry="2.35" fill="#4E4549"/>
      <ellipse cx="24" cy="31" rx="2.25" ry="1.55" fill="#F2BC38" stroke="#B98318" strokeWidth=".75"/>
      <path d="M13.5 29.5 5 28M13.5 32 5.5 33M34.5 29.5 43 28M34.5 32l8 1" stroke="#574C51" strokeWidth="1.65" strokeLinecap="round"/>
      <path d="M34.5 12.5c-3.5-4.5-7.6-1.7-6.5 2.1 1 3.4 4.6 5.1 6.5 5.8 1.9-.7 5.5-2.4 6.5-5.8 1.1-3.8-3-6.6-6.5-2.1Z" fill="#EB4E67" stroke="#A92F47" strokeWidth="1.4"/>
      <circle cx="34.5" cy="16.3" r="2.25" fill="#F36C80" stroke="#A92F47" strokeWidth="1.1"/>
    </svg>
  );
}

function bankThemeColor(bank) {
  if (bank.id === 'bank_topup') return '#777481';
  if (bank.id === 'bank_debt') return '#E46F9F';
  if (bank.id === 'bank_japan') return '#C77D9C';
  return bank.color || '#EC6F9E';
}

function BankCharacterIcon({ bank, size = 42 }) {
  const variant = bank.id === 'bank_topup' ? 'tabby' : bank.id === 'bank_debt' ? 'bunny' : bank.id === 'bank_japan' ? 'fox' : 'kitty';
  if (variant === 'bunny') return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none" aria-hidden="true">
      <path d="M12.7 21C6.8 11 8.6 3.7 13 4.5c4.5.8 6.6 9.3 7.2 14M35.3 21c5.9-10 4.1-17.3-.3-16.5-4.5.8-6.6 9.3-7.2 14" fill="#F7A7C8" stroke="#A94B72" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M7 29c0-10 7.4-17 17-17s17 7 17 17-7.4 15-17 15S7 39 7 29Z" fill="#F39AC0" stroke="#A94B72" strokeWidth="2"/>
      <ellipse cx="24" cy="29" rx="11.6" ry="10.2" fill="#FFFDFB" stroke="#D77CA2" strokeWidth="1.2"/>
      <ellipse cx="19.7" cy="28" rx="1.35" ry="1.9" fill="#55494E"/><ellipse cx="28.3" cy="28" rx="1.35" ry="1.9" fill="#55494E"/>
      <ellipse cx="24" cy="32" rx="1.8" ry="1.25" fill="#F1BE3C" stroke="#B9841B" strokeWidth=".6"/>
      <path d="M32.8 17.8c-3.4-3.6-6.4-.9-5 2.1 1.1 2.4 3.7 3.5 5 4 1.3-.5 3.9-1.6 5-4 1.4-3-1.6-5.7-5-2.1Z" fill="#E84D86" stroke="#A63861" strokeWidth="1.2"/>
      <circle cx="32.8" cy="21" r="1.8" fill="#F56E9D"/>
    </svg>
  );
  if (variant === 'fox') return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none" aria-hidden="true">
      <path d="M8.5 20 10.5 5l11 8h5l11-8 2 15c1.8 2.5 2.5 5.5 2.5 8.5C42 38 34.3 44 24 44S6 38 6 28.5c0-3 .7-6 2.5-8.5Z" fill="#DFA0B7" stroke="#87556A" strokeWidth="2" strokeLinejoin="round"/>
      <path d="m12 9 8.5 6.8-10.3 4.4L12 9Zm24 0-8.5 6.8 10.3 4.4L36 9Z" fill="#F7D9E3"/>
      <path d="M13.5 30c3.1-2.8 6.7-2.3 10.5.5 3.8-2.8 7.4-3.3 10.5-.5-.9 7.8-4.8 11.8-10.5 11.8S14.4 37.8 13.5 30Z" fill="#FFF8F5"/>
      <ellipse cx="18.4" cy="27" rx="2.1" ry="2.65" fill="#6186A7" stroke="#544C55" strokeWidth="1"/><ellipse cx="29.6" cy="27" rx="2.1" ry="2.65" fill="#6186A7" stroke="#544C55" strokeWidth="1"/>
      <circle cx="17.8" cy="26.2" r=".65" fill="#fff"/><circle cx="29" cy="26.2" r=".65" fill="#fff"/>
      <path d="m21.8 32.2 2.2-1.1 2.2 1.1-2.2 2.1-2.2-2.1Z" fill="#6B505C"/>
      <path d="M34.5 14.4c1.1-3.5 5.3-3.8 6.1-.3.6 2.8-2 5.3-5 6.8-2.9-1.1-5.2-3.4-4.5-5.5.5-1.5 2-1.9 3.4-1Z" fill="#A88BD1" stroke="#705A96" strokeWidth="1.1"/>
      <circle cx="35.5" cy="16.7" r="1.2" fill="#F2D8FF"/>
    </svg>
  );
  if (variant === 'tabby') return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none" aria-hidden="true">
      <path d="M37 32c8-3 10 3 7 7-1.8 2.4-5.1 2.7-8 1" stroke="#625F67" strokeWidth="7" strokeLinecap="round"/>
      <path d="M42.5 33.2 40 38M45 36.2l-5 1.5" stroke="#918E96" strokeWidth="1.8" strokeLinecap="round"/>
      <path d="M9 23c0-4.5 1.4-8.1 4-10.5V7l6.2 4.5c1.5-.5 3.1-.7 4.8-.7s3.3.2 4.8.7L35 7v5.5c2.6 2.4 4 6 4 10.5v8.2C39 39.8 33.5 44 24 44S9 39.8 9 31.2V23Z" fill="#B9B7BE" stroke="#5C5961" strokeWidth="2.1" strokeLinejoin="round"/>
      <path d="m14.8 10.3 3.5 2.5-3.7 1.3.2-3.8Zm18.4 0-3.5 2.5 3.7 1.3-.2-3.8Z" fill="#E5B7C1"/>
      <path d="M20.3 11.8 21.5 16M24 11v4.7M27.7 11.8 26.5 16M10.5 27l4 1M37.5 27l-4 1" stroke="#7E7B83" strokeWidth="2" strokeLinecap="round"/>
      <circle cx="18.3" cy="23.7" r="1.65" fill="#4D4A50"/><circle cx="29.7" cy="23.7" r="1.65" fill="#4D4A50"/>
      <circle cx="14.8" cy="28.4" r="2.2" fill="#DFA6B2" opacity=".72"/><circle cx="33.2" cy="28.4" r="2.2" fill="#DFA6B2" opacity=".72"/>
      <path d="m22 27.2 2-1 2 1-2 1.8-2-1.8Z" fill="#66535D"/>
      <path d="M24 29c-.2 2-3.2 2.6-4.2.8M24 29c.2 2 3.2 2.6 4.2.8M15 26.2 7.5 25M15 29 7 30M33 26.2l7.5-1.2M33 29l8 1" stroke="#56525A" strokeWidth="1.45" strokeLinecap="round"/>
      <path d="M14 39.5c0-2 1.5-3.5 3.5-3.5s3.5 1.5 3.5 3.5M27 39.5c0-2 1.5-3.5 3.5-3.5s3.5 1.5 3.5 3.5" fill="#CFCDD2" stroke="#77747C" strokeWidth="1.35" strokeLinecap="round"/>
      <circle cx="17" cy="39.7" r=".65" fill="#817D85"/><circle cx="19" cy="39.2" r=".65" fill="#817D85"/><circle cx="29" cy="39.2" r=".65" fill="#817D85"/><circle cx="31" cy="39.7" r=".65" fill="#817D85"/>
    </svg>
  );
  return <KittyProjectIcon size={size}/>;
}

function piggyBalance(bank) {
  return Number(bank.openingBalance || 0) + bank.transactions.reduce((sum, tx) =>
    sum + (tx.kind === 'income' ? Number(tx.amount || 0) : -Number(tx.amount || 0)), 0);
}

function baht(value) {
  return `฿${Number(value || 0).toLocaleString('en-US', { maximumFractionDigits: 2 })}`;
}

function PiggyBankPage({ project, toast }) {
  useStore();
  const fresh = Store.get().projects.find(p => p.id === project.id) || project;
  const [selectedId, setSelectedId] = usePiggyState(null);
  const [modal, setModal] = usePiggyState(null);
  const [photo, setPhoto] = usePiggyState(null);
  const selected = fresh.banks.find(b => b.id === selectedId);

  function openBank(bank) {
    setSelectedId(bank.id);
    if (bank.openingBalance == null) setModal({ kind:'setup', bank });
  }

  if (selected) {
    return <PiggyBankDetail bank={selected} onBack={() => setSelectedId(null)}
      onSetup={() => setModal({ kind:'setup', bank:selected })}
      onAdd={(kind) => setModal({ kind:'transaction', bank:selected, transactionKind:kind })}
      onPhoto={setPhoto} toast={toast}
      modal={modal} setModal={setModal} photo={photo} setPhoto={setPhoto} />;
  }

  const total = fresh.banks.reduce((sum, bank) => sum + piggyBalance(bank), 0);
  return (
    <div className="piggy-page fade-in">
      <section className="piggy-hero">
        <div className="piggy-hero-copy">
          <span className="piggy-kicker">OUR SAVINGS</span>
          <h2>Little jars, lovely plans</h2>
          <p>Keep every shared goal in its own place and watch it grow together.</p>
        </div>
        <div className="piggy-total">
          <KittyProjectIcon size={48} />
          <div><span>Total saved</span><strong>{baht(total)}</strong></div>
        </div>
      </section>

      <div className="section-head piggy-section-head">
        <div><h3>Your kitty banks</h3><p>{fresh.banks.length} savings jars</p></div>
        <button className="btn btn-primary btn-sm" onClick={() => setModal({kind:'new-bank'})}>＋ Add kitty bank</button>
      </div>

      <div className="piggy-grid">
        {fresh.banks.map((bank, index) => {
          const balance = piggyBalance(bank);
          const last = bank.transactions[0];
          const themeColor = bankThemeColor(bank);
          return (
            <button className="piggy-card" key={bank.id} onClick={() => openBank(bank)}
              style={{ '--bank': themeColor, '--bank-soft': tint(themeColor, .16) }}>
              <div className="piggy-card-top">
                <div className="piggy-jar-icon"><BankCharacterIcon bank={bank} size={43} /></div>
                <span className="piggy-number">{String(index + 1).padStart(2,'0')}</span>
              </div>
              <div className="piggy-name">{bank.name}</div>
              <div className="piggy-balance">{bank.openingBalance == null ? 'Set opening amount' : baht(balance)}</div>
              <div className="piggy-card-foot">
                <span>{last ? `${last.kind === 'income' ? '+' : '−'}${baht(last.amount)} · ${relDate(last.date)}` : 'No activity yet'}</span>
                <span className="piggy-arrow">→</span>
              </div>
            </button>
          );
        })}
      </div>

      {modal?.kind === 'new-bank' && <NewPiggyBankModal onClose={() => setModal(null)} toast={toast} />}
    </div>
  );
}

function PiggyBankDetail({ bank, onBack, onSetup, onAdd, onPhoto, toast, modal, setModal, photo, setPhoto }) {
  const balance = piggyBalance(bank);
  const themeColor = bankThemeColor(bank);
  const moneyIn = bank.transactions.filter(tx => tx.kind === 'income').reduce((s,tx) => s + Number(tx.amount || 0), 0);
  const moneyOut = bank.transactions.filter(tx => tx.kind === 'expense').reduce((s,tx) => s + Number(tx.amount || 0), 0);

  return (
    <div className="piggy-detail fade-in">
      <button className="piggy-back" onClick={onBack}>← All kitty banks</button>
      <section className="piggy-detail-hero" style={{ '--bank':themeColor, '--bank-soft':tint(themeColor,.16) }}>
        <div className="piggy-detail-icon"><BankCharacterIcon bank={bank} size={62}/></div>
        <div className="piggy-detail-main">
          <span>SAVINGS JAR</span><h2>{bank.name}</h2>
          <button onClick={onSetup}>{bank.openingBalance == null ? 'Set opening amount' : `Opening amount ${baht(bank.openingBalance)} · Edit`}</button>
        </div>
        <div className="piggy-detail-balance"><span>Current balance</span><strong>{baht(balance)}</strong></div>
      </section>

      <div className="piggy-actions">
        <button className="piggy-action piggy-action-in" onClick={() => onAdd('income')}><b>＋</b><span>Money in<small>Add savings</small></span></button>
        <button className="piggy-action piggy-action-out" onClick={() => onAdd('expense')}><b>−</b><span>Money out<small>Record spending</small></span></button>
      </div>

      <div className="piggy-summary">
        <div><span>Money in</span><strong className="positive">+{baht(moneyIn)}</strong></div>
        <div><span>Money out</span><strong className="negative">−{baht(moneyOut)}</strong></div>
        <div><span>Transactions</span><strong>{bank.transactions.length}</strong></div>
      </div>

      <div className="section-head"><h3>Activity log</h3></div>
      {bank.transactions.length === 0 ? (
        <div className="piggy-empty"><BankCharacterIcon bank={bank} size={50}/><h3>No activity yet</h3><p>Add money to start growing this kitty bank.</p></div>
      ) : (
        <div className="piggy-log">
          {bank.transactions.map(tx => (
            <div className="piggy-log-row" key={tx.id}>
              <div className={`piggy-log-sign ${tx.kind}`} >{tx.kind === 'income' ? '+' : '−'}</div>
              <div className="piggy-log-copy">
                <div className="piggy-log-title">{tx.kind === 'income' ? `From ${tx.person || 'Unknown'}` : `Spent by ${tx.person || 'Unknown'}`}</div>
                <div className="piggy-log-meta">{relDate(tx.date)}{tx.note ? ` · ${tx.note}` : ''}</div>
              </div>
              {tx.photo && <button className="piggy-thumb" onClick={() => onPhoto(tx.photo)} aria-label="View attached photo"><img src={tx.photo} alt="Receipt attachment" /></button>}
              <div className={`piggy-log-amount ${tx.kind}`}>{tx.kind === 'income' ? '+' : '−'}{baht(tx.amount)}</div>
              <button className="piggy-delete" title="Delete entry" onClick={() => {
                if (confirm('Delete this activity?')) { Store.deletePiggyTransaction(bank.id, tx.id); toast('Activity deleted'); }
              }}>×</button>
            </div>
          ))}
        </div>
      )}

      {modal?.kind === 'setup' && <OpeningBalanceModal bank={bank} onClose={() => setModal(null)} toast={toast} />}
      {modal?.kind === 'transaction' && <PiggyTransactionModal bank={bank} kind={modal.transactionKind} onClose={() => setModal(null)} toast={toast} />}
      {photo && <PhotoViewer photo={photo} onClose={() => setPhoto(null)} />}
    </div>
  );
}

function OpeningBalanceModal({ bank, onClose, toast }) {
  const [amount, setAmount] = usePiggyState(bank.openingBalance == null ? '' : bank.openingBalance);
  function save() {
    if (amount === '' || Number(amount) < 0) return toast('Enter the opening amount');
    Store.updatePiggyBank(bank.id, { openingBalance:Number(amount) });
    toast('Opening amount saved ✨'); onClose();
  }
  return (
    <Modal title="Opening amount" onClose={onClose} icon={<div className="piggy-modal-icon"><BankCharacterIcon bank={bank} size={31}/></div>}>
      <p className="muted piggy-modal-intro">How much is already inside “{bank.name}” right now?</p>
      <div className="field"><label>Starting balance (THB)</label><div className="piggy-money-input"><span>฿</span><input autoFocus type="number" min="0" inputMode="decimal" value={amount} onChange={e=>setAmount(e.target.value)} placeholder="0" /></div></div>
      <button className="btn btn-primary piggy-full" onClick={save}>Save opening amount</button>
    </Modal>
  );
}

function NewPiggyBankModal({ onClose, toast }) {
  const [name, setName] = usePiggyState('');
  const [amount, setAmount] = usePiggyState('');
  const [color, setColor] = usePiggyState(PIGGY_COLORS[0]);
  function save() {
    if (!name.trim()) return toast('Name your kitty bank');
    Store.addPiggyBank({ name:name.trim(), openingBalance:amount === '' ? null : Number(amount), color });
    toast('New kitty bank added ✨'); onClose();
  }
  return (
    <Modal title="New kitty bank" onClose={onClose} icon={<div className="piggy-modal-icon"><KittyProjectIcon size={28}/></div>}>
      <div className="field"><label>Name</label><input className="input" autoFocus value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. New laptop" /></div>
      <div className="field"><label>Opening amount (optional)</label><div className="piggy-money-input"><span>฿</span><input type="number" min="0" inputMode="decimal" value={amount} onChange={e=>setAmount(e.target.value)} placeholder="0" /></div></div>
      <div className="field"><label>Color</label><div className="piggy-color-row">{PIGGY_COLORS.map(c=><button key={c} className={c===color?'on':''} style={{background:c}} onClick={()=>setColor(c)} aria-label={`Choose ${c}`} />)}</div></div>
      <button className="btn btn-primary piggy-full" onClick={save}>Add kitty bank</button>
    </Modal>
  );
}

function PiggyTransactionModal({ bank, kind, onClose, toast }) {
  const [amount, setAmount] = usePiggyState('');
  const [person, setPerson] = usePiggyState('');
  const [note, setNote] = usePiggyState('');
  const [date, setDate] = usePiggyState(new Date().toISOString().slice(0,10));
  const [photo, setPhoto] = usePiggyState('');
  const [photoBusy, setPhotoBusy] = usePiggyState(false);
  const income = kind === 'income';

  async function choosePhoto(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setPhotoBusy(true);
    try { setPhoto(await compressPiggyPhoto(file)); }
    catch (err) { toast(err.message || 'Could not add that photo'); }
    setPhotoBusy(false);
  }

  function save() {
    if (!amount || Number(amount) <= 0) return toast('Enter an amount');
    if (!date) return toast('Choose a date');
    if (photo && Store.exportJSON().length + photo.length > 420000) {
      return toast('Photo storage is nearly full. Save this entry without the photo.');
    }
    Store.addPiggyTransaction(bank.id, { kind, amount:Number(amount), person:person.trim(), note:note.trim(), date, photo });
    toast(income ? 'Money added ✨' : 'Spending recorded'); onClose();
  }

  return (
    <Modal title={income ? 'Money in' : 'Money out'} onClose={onClose} icon={<div className={`piggy-modal-sign ${kind}`}>{income?'+':'−'}</div>}>
      <div className="field"><label>Amount (THB)</label><div className="piggy-money-input"><span>฿</span><input autoFocus type="number" min="0" inputMode="decimal" value={amount} onChange={e=>setAmount(e.target.value)} placeholder="0" /></div></div>
      <div className="field"><label>{income ? 'Received from' : 'Spent by'}</label><input className="input" value={person} onChange={e=>setPerson(e.target.value)} placeholder="View, Mimi, someone else…" /></div>
      <div className="field"><label>Date</label><input className="input" type="date" value={date} onChange={e=>setDate(e.target.value)} /></div>
      <div className="field"><label>Note (optional)</label><textarea className="textarea" value={note} onChange={e=>setNote(e.target.value)} placeholder={income ? 'What is this money for?' : 'What did you spend it on?'} /></div>
      <div className="field"><label>Photo (optional)</label>
        {photo ? <div className="piggy-photo-preview"><img src={photo} alt="Attachment preview"/><button onClick={()=>setPhoto('')}>Remove</button></div> :
          <label className="piggy-photo-picker">{photoBusy ? 'Preparing photo…' : '＋ Add a receipt or photo'}<input type="file" accept="image/*" onChange={choosePhoto} disabled={photoBusy}/></label>}
        <p className="faint piggy-photo-help">Photos are compressed before syncing to keep the shared ledger light.</p>
      </div>
      <button className={`btn piggy-full ${income?'piggy-save-in':'piggy-save-out'}`} onClick={save}>{income ? 'Add money' : 'Record spending'}</button>
    </Modal>
  );
}

function compressPiggyPhoto(file) {
  if (!file.type.startsWith('image/')) return Promise.reject(new Error('Choose an image file'));
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = () => reject(new Error('Could not read that photo'));
    reader.onload = () => {
      const img = new Image();
      img.onerror = () => reject(new Error('Could not open that photo'));
      img.onload = () => {
        const max = 720;
        const scale = Math.min(1, max / Math.max(img.width, img.height));
        const canvas = document.createElement('canvas');
        canvas.width = Math.max(1, Math.round(img.width * scale));
        canvas.height = Math.max(1, Math.round(img.height * scale));
        canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
        let data = canvas.toDataURL('image/jpeg', .68);
        if (data.length > 100000) data = canvas.toDataURL('image/jpeg', .46);
        if (data.length > 130000) return reject(new Error('This photo is still too large. Try a smaller image.'));
        resolve(data);
      };
      img.src = reader.result;
    };
    reader.readAsDataURL(file);
  });
}

function PhotoViewer({ photo, onClose }) {
  return <div className="piggy-photo-viewer" onClick={onClose}><button aria-label="Close photo">×</button><img src={photo} alt="Attached receipt" onClick={e=>e.stopPropagation()} /></div>;
}

Object.assign(window, { PiggyBankPage, KittyProjectIcon });
