// Split Crew — add expense + currency + settle screens

// Curated SEK-baseline rates kept as a final-fallback ONLY. The real source
// is `pot.fxRates` (snapshotted at trip-create from exchangerate.host) — it's
// always preferred when present.
const FX_FALLBACK_SEK = { SEK: 1, EUR: 11.48, USD: 10.62, NOK: 0.99, GBP: 13.55, DKK: 1.54, CHF: 12.12, JPY: 0.07, ISK: 0.076, PLN: 2.66, CZK: 0.46, AUD: 6.85, CAD: 7.78, NZD: 6.32 };
// Back-compat alias (older code referenced `FX[currency]` directly).
const FX = FX_FALLBACK_SEK;

// Convert `amount` from `fromCurrency` to `toCurrency` using the rate map
// snapshotted on the trip. The map's shape is: rate[X] = how many BASE units
// 1 X is worth, where BASE is the trip's home currency.
//
// Returns the converted amount as a Number. If a rate is missing it falls
// through to the SEK baseline (so old trips and offline mode still work).
function convert(amount, fromCurrency, toCurrency, ratesMap, baseCurrency) {
  const a = Number(amount) || 0;
  const from = (fromCurrency || 'SEK').toUpperCase();
  const to = (toCurrency || 'SEK').toUpperCase();
  if (from === to) return a;
  const base = (baseCurrency || 'SEK').toUpperCase();
  // Path: from → base → to using ratesMap (keyed off base).
  const r = ratesMap || null;
  // amount in base = amount * r[from]   (since r[from] = base per 1 from)
  // amount in to   = amountInBase / r[to]
  const fromToBase = (r && r[from] != null) ? Number(r[from]) : (FX_FALLBACK_SEK[from] / FX_FALLBACK_SEK[base]);
  const toToBase = (r && r[to] != null) ? Number(r[to]) : (FX_FALLBACK_SEK[to] / FX_FALLBACK_SEK[base]);
  if (!fromToBase || !toToBase) return a; // give up gracefully
  const inBase = a * fromToBase;
  return inBase / toToBase;
}

// Format an amount with thin-space thousand separators (sv-SE).
function fmtAmount(n) {
  return Math.round(Number(n) || 0).toLocaleString('sv-SE').replace(/,/g, ' ');
}

// Currency catalogue used by both AddExpense and the picker.
const CURRENCIES = [
  { c: 'SEK', flag: '🇸🇪', name: 'Swedish krona' },
  { c: 'EUR', flag: '🇪🇺', name: 'Euro' },
  { c: 'USD', flag: '🇺🇸', name: 'US dollar' },
  { c: 'NOK', flag: '🇳🇴', name: 'Norwegian krone' },
  { c: 'DKK', flag: '🇩🇰', name: 'Danish krone' },
  { c: 'GBP', flag: '🇬🇧', name: 'British pound' },
  { c: 'CHF', flag: '🇨🇭', name: 'Swiss franc' },
  { c: 'JPY', flag: '🇯🇵', name: 'Japanese yen' },
  { c: 'ISK', flag: '🇮🇸', name: 'Icelandic krona' },
  { c: 'PLN', flag: '🇵🇱', name: 'Polish złoty' },
  { c: 'CZK', flag: '🇨🇿', name: 'Czech koruna' },
  { c: 'AUD', flag: '🇦🇺', name: 'Australian dollar' },
  { c: 'CAD', flag: '🇨🇦', name: 'Canadian dollar' },
  { c: 'NZD', flag: '🇳🇿', name: 'New Zealand dollar' },
];

// ═══════════════════════════════════════════════════════════════
// ADD EXPENSE
// ═══════════════════════════════════════════════════════════════
function AddExpenseAppScreen({ ctx }) {
  const [me] = useMe();
  const myName = ctx.myName || (me.name || 'Du');

  // Trip's home currency (was picked at create-name) and FX snapshot.
  const homeCurrency = (ctx.pot && ctx.pot.homeCurrency) || 'SEK';
  const fxRates = (ctx.pot && ctx.pot.fxRates) || null;

  // Default the expense currency to whatever the user last picked for THIS
  // trip on the currency screen. If they haven't picked anything yet, fall
  // back to the trip's home currency. ctx.newExp.currency carries the
  // selection across the AddExpense → Currency → AddExpense round-trip.
  const initialCurrency = (ctx.newExp && ctx.newExp.currency) || homeCurrency;

  const [amount, setAmount] = React.useState('');
  const [currency, setCurrency] = React.useState(initialCurrency);
  // Keep ctx.newExp in sync so the currency picker can read/write it.
  React.useEffect(() => {
    if (ctx.setNewExp) ctx.setNewExp(prev => ({ ...prev, currency }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currency]);

  const [category, setCategory] = React.useState(null);
  const [desc, setDesc] = React.useState('');
  const [paidBy, setPaidBy] = React.useState(myName);
  // Split defaults: split evenly across every crew member.
  const initialSplit = React.useMemo(() => {
    const obj = {};
    const members = (ctx.pot && ctx.pot.members && ctx.pot.members.length) ? ctx.pot.members : [myName];
    members.forEach(m => { obj[m] = true; });
    return obj;
  }, []);
  const [splitWith, setSplitWith] = React.useState(initialSplit);
  const [showReceipt, setShowReceipt] = React.useState(false);

  // Convert entered amount → home currency (canonical for debt math)
  // and → SEK (always shown as a reference).
  const amtNum = Number(amount || 0);
  const amtInHome = convert(amtNum, currency, homeCurrency, fxRates, homeCurrency);
  const amtInSek = convert(amtNum, currency, 'SEK', fxRates, homeCurrency);
  const count = Object.values(splitWith).filter(Boolean).length || 1;
  const perPersonHome = amtInHome / count;

  const cats = [
    { k: 'food', i: '🍴', label: 'Food' },
    { k: 'drinks', i: '🥃', label: 'Drinks' },
    { k: 'lodging', i: '🏠', label: 'Lodging' },
    { k: 'transit', i: '🚆', label: 'Travel' },
    { k: 'tickets', i: '🎫', label: 'Tickets' },
    { k: 'other', i: '•••', label: 'Other' },
  ];
  // Build crew list from the pot's actual members (no default friends).
  const crewNames = (ctx.pot && ctx.pot.members && ctx.pot.members.length) ? ctx.pot.members : [myName];
  const crewColorFor = (name, i) => {
    if (name === myName) return PEOPLE_COLORS.Y;
    const palette = [PEOPLE_COLORS.E, PEOPLE_COLORS.M, PEOPLE_COLORS.S, PEOPLE_COLORS.L];
    return palette[i % palette.length];
  };

  const save = () => {
    const newExp = {
      id: Date.now(),
      desc,
      cat: category,
      amount: amtNum,
      currency,
      // Canonical debt-math number is always in the trip's home currency.
      home: Math.round(amtInHome),
      homeCurrency,
      // SEK is always carried as a stable reference (DB column `sek_amount`).
      sek: Math.round(amtInSek),
      paidBy,
      splitWith: Object.keys(splitWith).filter(k => splitWith[k]),
      date: 'nu',
    };
    if (ctx.addExpense) {
      ctx.addExpense(newExp);
    } else {
      ctx.setExpenses([newExp, ...ctx.expenses]);
    }
    ctx.go('dashboard');
  };

  return (
    <div>
      <AppHeader back={() => ctx.go('dashboard')} title="NEW EXPENSE" right={
        <button onClick={() => setShowReceipt(true)} style={{
          background: 'transparent', border: 'none', color: 'var(--cyan-500)', cursor: 'pointer', padding: 0,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 8h18M8 21V8"/></svg>
        </button>
      } />

      {showReceipt && <ReceiptScanOverlay onClose={() => { setShowReceipt(false); setAmount('124'); setDesc('Dinner'); setCategory('food'); }} />}

      <div style={{ padding: '0 24px 100px' }}>
        {/* Amount with currency selector */}
        <div className="bracket" style={{
          padding: '18px 14px', border: '1px solid var(--cyan-500)',
          background: 'rgba(59,180,232,0.04)', textAlign: 'center', marginBottom: 14,
        }}>
          <button onClick={() => ctx.go('currency')} style={{
            background: 'transparent', border: '1px solid var(--line)', color: 'var(--cyan-500)',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 11,
            letterSpacing: '0.2em', padding: '4px 10px', cursor: 'pointer', marginBottom: 10,
          }}>{currency} ↓</button>
          <div style={{
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 56, lineHeight: 1,
            color: 'var(--text-hi)', letterSpacing: '-0.02em',
          }}>{amount || '0'}<span style={{ color: 'var(--cyan-500)', animation: 'blink 1s steps(2) infinite' }}>|</span></div>

          {/* Conversion line: show ≈ home currency when entered ≠ home;
              additionally show SEK reference when home ≠ SEK. */}
          {(currency !== homeCurrency || homeCurrency !== 'SEK') && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 6 }}>
              {currency !== homeCurrency && (
                <div style={{ fontSize: 12, color: 'var(--cyan-500)', fontFamily: 'var(--font-display)', letterSpacing: '0.12em' }}>
                  ≈ {fmtAmount(amtInHome)} {homeCurrency}
                </div>
              )}
              {homeCurrency !== 'SEK' && currency !== 'SEK' && (
                <div style={{ fontSize: 11, color: 'var(--text-mu)', fontFamily: 'var(--font-display)', letterSpacing: '0.12em' }}>
                  ≈ {fmtAmount(amtInSek)} SEK
                </div>
              )}
            </div>
          )}

          <div style={{ fontSize: 10, color: 'var(--text-mu)', marginTop: 6, fontFamily: 'var(--font-display)', letterSpacing: '0.18em' }}>
            {fmtAmount(perPersonHome)} {homeCurrency} / PERSON
          </div>
        </div>

        {/* Scan receipt — fills amount + description from receipt */}
        <button onClick={() => setShowReceipt(true)} style={{
          width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          padding: '12px 14px', marginBottom: 14,
          background: 'rgba(59,180,232,0.06)',
          border: '1px dashed var(--cyan-500)',
          color: 'var(--cyan-100)', cursor: 'pointer',
          fontFamily: 'var(--font-display)', letterSpacing: '0.2em', fontSize: 11, fontWeight: 600,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 8h18M8 21V8"/><path d="M13 13h4M13 16h4" strokeLinecap="round"/></svg>
          SCAN RECEIPT
          <span style={{ fontSize: 9, color: 'var(--text-mu)', letterSpacing: '0.14em' }}>◉ OCR</span>
        </button>

        {/* Numpad */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4, marginBottom: 14 }}>
          {['1','2','3','4','5','6','7','8','9','.','0','⌫'].map(k => (
            <button key={k} onClick={() => {
              if (k === '⌫') setAmount(a => a.slice(0, -1));
              else setAmount(a => (a + k).replace(/^0(?=\d)/, ''));
            }} style={{
              padding: '10px', background: 'rgba(10,20,32,0.5)',
              border: '1px solid var(--line-subtle)', color: 'var(--text-hi)',
              fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18, cursor: 'pointer',
            }}>{k}</button>
          ))}
        </div>

        {/* Description */}
        <div style={{ marginBottom: 14, border: '1px solid var(--line-subtle)', padding: '8px 12px', background: 'rgba(10,20,32,0.4)' }}>
          <div style={{ fontSize: 9, letterSpacing: '0.22em', color: 'var(--text-mu)', fontFamily: 'var(--font-display)' }}>DESCRIPTION</div>
          <input value={desc} onChange={e => setDesc(e.target.value)} style={{
            background: 'transparent', border: 'none', outline: 'none',
            color: 'var(--text-hi)', fontSize: 14, width: '100%', padding: '2px 0',
          }} />
        </div>

        {/* Categories */}
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 9, letterSpacing: '0.22em', color: 'var(--text-mu)', fontFamily: 'var(--font-display)', marginBottom: 8 }}>CATEGORY · AUTO-DETECTED ◆</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 4 }}>
            {cats.map(c => (
              <button key={c.k} onClick={() => setCategory(c.k)} style={{
                padding: '8px 2px 6px', cursor: 'pointer',
                background: category === c.k ? 'rgba(59,180,232,0.15)' : 'transparent',
                border: '1px solid ' + (category === c.k ? 'var(--cyan-500)' : 'var(--line-subtle)'),
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                color: category === c.k ? 'var(--cyan-100)' : 'var(--text-mu)',
              }}>
                <span style={{ fontSize: 16, lineHeight: 1 }}>{c.i}</span>
                <span style={{
                  fontSize: 8, letterSpacing: '0.14em',
                  fontFamily: 'var(--font-display)', fontWeight: 600,
                  textTransform: 'uppercase', lineHeight: 1,
                }}>{c.label}</span>
              </button>
            ))}
          </div>
        </div>

        <div style={{ marginBottom: 18 }} />

        <PrimaryBtn onClick={save} pulse>Add expense · {fmtAmount(amtNum)} {currency}</PrimaryBtn>
      </div>
    </div>
  );
}

function ReceiptScanOverlay({ onClose }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.94)', zIndex: 200,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div style={{ fontFamily: 'var(--font-display)', color: 'var(--cyan-500)', letterSpacing: '0.28em', fontSize: 11, marginBottom: 14 }}>◉ SCANNING RECEIPT</div>
      <div style={{
        width: 240, height: 320, border: '1px solid var(--cyan-500)', position: 'relative',
        background: 'linear-gradient(180deg, rgba(255,255,255,0.94), rgba(255,255,255,0.9))',
        boxShadow: '0 0 40px rgba(59,180,232,0.3)',
      }}>
        <div style={{ padding: 14, color: '#222', fontFamily: 'ui-monospace', fontSize: 10, lineHeight: 1.6 }}>
          <div style={{ textAlign: 'center', fontWeight: 700 }}>RISTORANTE MILANO</div>
          <div style={{ textAlign: 'center', opacity: 0.6 }}>Via Dante 14 · Milano</div>
          <div style={{ borderTop: '1px dashed #888', margin: '8px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Antipasto</span><span>18,00</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Pasta al ragu</span><span>22,00</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Bistecca</span><span>38,00</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Vino rosso</span><span>28,00</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Caffè</span><span>12,00</span></div>
          <div style={{ borderTop: '1px dashed #888', margin: '8px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700 }}><span>TOTALE</span><span>124,00 €</span></div>
        </div>
        {/* scanning line */}
        <div style={{
          position: 'absolute', left: 0, right: 0, height: 2, top: '50%',
          background: 'var(--cyan-500)', boxShadow: '0 0 12px var(--cyan-500)',
          animation: 'scan 2s ease-in-out infinite',
        }} />
        {['tl','tr','bl','br'].map(c => (
          <div key={c} style={{
            position: 'absolute', width: 20, height: 20,
            [c.includes('t')?'top':'bottom']: -2, [c.includes('l')?'left':'right']: -2,
            borderTop: c.includes('t') ? '2px solid var(--cyan-500)' : 'none',
            borderBottom: c.includes('b') ? '2px solid var(--cyan-500)' : 'none',
            borderLeft: c.includes('l') ? '2px solid var(--cyan-500)' : 'none',
            borderRight: c.includes('r') ? '2px solid var(--cyan-500)' : 'none',
          }} />
        ))}
      </div>
      <div style={{ color: 'var(--text)', fontSize: 11, marginTop: 16, maxWidth: 240, textAlign: 'center', lineHeight: 1.5 }}>
        Detected <span style={{ color: 'var(--cyan-500)', fontFamily: 'var(--font-display)' }}>FOOD</span> · 124.00 EUR · Ristorante Milano
      </div>
      <button onClick={onClose} className="btn btn-primary" style={{ marginTop: 14, padding: '10px 22px' }}>Use</button>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// CURRENCY PICKER
// ═══════════════════════════════════════════════════════════════
// Lets the user pick the currency for THIS expense. The trip's home
// currency is fixed (set at trip creation) and shown as a reminder.
// Tapping a currency writes it onto ctx.newExp.currency and returns to
// the add-expense screen, which reads it as its initial currency state.
function CurrencyScreen({ ctx }) {
  const homeCurrency = (ctx.pot && ctx.pot.homeCurrency) || 'SEK';
  const fxRates = (ctx.pot && ctx.pot.fxRates) || null;
  const fxFetchedAt = (ctx.pot && ctx.pot.fxFetchedAt) || null;
  const fxSource = (ctx.pot && ctx.pot.fxSource) || null;
  const selected = (ctx.newExp && ctx.newExp.currency) || homeCurrency;

  const pick = (c) => {
    if (ctx.setNewExp) ctx.setNewExp(prev => ({ ...prev, currency: c }));
    ctx.go('add-expense');
  };

  // Show "1 X = Y home" so the user understands the conversion.
  const rateLabel = (c) => {
    if (c === homeCurrency) return `1 ${c} (home)`;
    const oneInHome = convert(1, c, homeCurrency, fxRates, homeCurrency);
    return `1 ${c} = ${oneInHome.toFixed(oneInHome < 1 ? 4 : 2)} ${homeCurrency}`;
  };

  const dateLabel = fxFetchedAt
    ? new Date(fxFetchedAt).toLocaleDateString('en-GB', { day: '2-digit', month: 'short' }).toUpperCase()
    : '— · —';

  return (
    <div>
      <AppHeader back={() => ctx.go('add-expense')} title="EXPENSE CURRENCY" />
      <div style={{ padding: '0 24px' }}>
        <div style={{ fontSize: 11, color: 'var(--text-mu)', marginBottom: 18, lineHeight: 1.5 }}>
          Pick the currency you paid in. Debts are tracked in this trip's home currency&nbsp;
          <span style={{ color: 'var(--cyan-500)', fontFamily: 'var(--font-display)' }}>{homeCurrency}</span>
          {homeCurrency !== 'SEK' && <> with a SEK reference shown on the settle screen</>}.
        </div>
        <div style={{ fontSize: 10, letterSpacing: '0.22em', color: 'var(--text-mu)', fontFamily: 'var(--font-display)', marginBottom: 10 }}>
          ◆ TRIP RATE · {dateLabel}{fxSource ? ' · ' + fxSource.toUpperCase() : ''}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {CURRENCIES.map(x => {
            const sel = selected === x.c;
            return (
              <button key={x.c} onClick={() => pick(x.c)} style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 14px', cursor: 'pointer', textAlign: 'left',
                background: sel ? 'rgba(59,180,232,0.08)' : 'transparent',
                border: '1px solid ' + (sel ? 'var(--cyan-500)' : 'var(--line-subtle)'),
              }}>
                <span style={{ fontSize: 22 }}>{x.flag}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, letterSpacing: '0.1em', color: 'var(--text-hi)', fontSize: 14 }}>{x.c}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-mu)' }}>{x.name}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 12, color: 'var(--text-hi)' }}>
                    {rateLabel(x.c)}
                  </div>
                  {sel && <div style={{ fontSize: 9, color: 'var(--cyan-500)', fontFamily: 'var(--font-display)', letterSpacing: '0.18em' }}>◉ SELECTED</div>}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AddExpenseAppScreen, CurrencyScreen, FX, FX_FALLBACK_SEK, convertFx: convert, fmtAmount });
