// views.jsx — Dashboard + Entries views (scoped to the active project)
const { useState: useS3, useMemo } = React;

/* helper: display an aggregated base-sum, in native currency if the set is single-currency */
function dispAgg(baseSum, singleCur) {
  if (singleCur) return fmtMoney(baseSum / (singleCur.rateToBase || 1), singleCur).text;
  return fmtBase(baseSum);
}
function aggregate(project) {
  const S = Store.get();
  const valued = project.entries.filter(e => e.value != null && !isNaN(e.value));
  const curIds = [...new Set(valued.map(e => e.currencyId).filter(Boolean))];
  const single = curIds.length === 1 ? S.currencies.find(c => c.id === curIds[0]) : null;

  const byOwner = {};
  S.owners.forEach(o => byOwner[o.id] = { spent: 0, have: 0, received: 0, count: 0 });
  const byType = {}; const byCur = {};
  let unsettled = 0;
  valued.forEach(e => {
    const base = toBase(e.value, Store.currency(e.currencyId));
    if (byOwner[e.owner]) { byOwner[e.owner][e.flow] += base; byOwner[e.owner].count++; }
    if (e.flow === 'spent') byType[e.typeId] = (byType[e.typeId] || 0) + base;
    const ck = e.currencyId || '_none';
    byCur[ck] = byCur[ck] || { native: 0, count: 0 };
    byCur[ck].native += Number(e.value); byCur[ck].count++;
    if (!e.settled) unsettled++;
  });
  return { single, byOwner, byType, byCur, unsettled, total: project.entries.length };
}

/* ============ DASHBOARD ============ */
function Dashboard({ project, onAdd, toast }) {
  const S = useStore().get();
  const a = useMemo(() => aggregate(project), [project, JSON.stringify(project.entries)]);

  if (project.entries.length === 0) {
    return <Empty icon={<Icon name="wallet" size={40} color="var(--rose)" />}
      title="This page is empty 🌸"
      sub="Add your first entry — a cost, a note, some shared coins. It saves automatically."
      action={<button className="btn btn-primary" onClick={onAdd}>＋ Add first entry</button>} />;
  }

  const typeRows = Object.entries(a.byType).sort((x,y) => y[1]-x[1]);
  const maxType = Math.max(...typeRows.map(r => r[1]), 1);

  return (
    <div className="fade-in">
      {/* owner cards */}
      <div className="grid grid-2">
        {S.owners.map(o => {
          const d = a.byOwner[o.id] || { spent:0, have:0, received:0, count:0 };
          return (
            <div className="stat" key={o.id} style={{ background: `linear-gradient(155deg, ${tint(o.color,0.18)}, ${tint(o.color,0.30)})` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <Avatar owner={o} size={34} />
                <div style={{ fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 16, color: shade(o.color,-30) }}>{o.name}</div>
              </div>
              <div style={{ display: 'flex', gap: 22 }}>
                <div>
                  <div className="faint" style={{ fontFamily:'var(--font-ui)', fontWeight:700, fontSize:11, letterSpacing:'.04em' }}>SPENT</div>
                  <div style={{ fontFamily:'var(--font-ui)', fontWeight:700, fontSize:24, color: shade(o.color,-34), letterSpacing:'-.02em' }}>{dispAgg(d.spent, a.single)}</div>
                </div>
                <div>
                  <div className="faint" style={{ fontFamily:'var(--font-ui)', fontWeight:700, fontSize:11, letterSpacing:'.04em' }}>HOLDING</div>
                  <div style={{ fontFamily:'var(--font-ui)', fontWeight:700, fontSize:24, color: shade(o.color,-20), letterSpacing:'-.02em' }}>{dispAgg(d.have, a.single)}</div>
                </div>
              </div>
              <div style={{ marginTop:10, fontSize:12.5, fontWeight:600, color: shade(o.color,-14), opacity:.85 }}>
                {d.count} {d.count===1?'entry':'entries'}{d.received>0 ? ` · got ${dispAgg(d.received, a.single)}` : ''}
              </div>
            </div>
          );
        })}
      </div>

      {/* by type + by currency */}
      <div className="grid grid-2" style={{ marginTop: 16, alignItems: 'start' }}>
        <div className="card">
          <h3 style={{ fontSize: 15, marginBottom: 16 }}>Spending by type</h3>
          {typeRows.length === 0 ? <p className="muted" style={{ fontSize: 13 }}>No spending yet — only notes or holdings.</p> : (
            <div className="bars">
              {typeRows.slice(0,7).map(([tid, val]) => {
                const t = Store.type(tid);
                return (
                  <div className="bar-row" key={tid}>
                    <div className="bar-label"><IconBadge name={t?.icon||'coin'} color={t?.color||'#999'} size={26} /> {t?.name||'—'}</div>
                    <div className="bar-track"><div className="bar-fill" style={{ width: `${Math.max(8, val/maxType*100)}%`, background: `linear-gradient(90deg, ${t?.color}, ${shade(t?.color||'#EC6F9E',18)})` }} /></div>
                    <div className="bar-val" style={{ color: shade(t?.color||'#999',-18) }}>{dispAgg(val, a.single)}</div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <div className="card">
          <h3 style={{ fontSize: 15, marginBottom: 16 }}>By currency</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {Object.entries(a.byCur).map(([cid, d]) => {
              const c = cid === '_none' ? null : Store.currency(cid);
              return (
                <div key={cid} style={{ display:'flex', alignItems:'center', gap:11 }}>
                  <div style={{ width:34, height:34, borderRadius:11, display:'grid', placeItems:'center', background: tint(c?.color||'#B5A3AD',0.16), color: c?.color||'#B5A3AD', fontFamily:'var(--font-ui)', fontWeight:700 }}>{c?c.symbol:'—'}</div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontFamily:'var(--font-ui)', fontWeight:600, fontSize:14 }}>{c?c.code:'No currency'}</div>
                    <div className="faint" style={{ fontSize:11.5, fontWeight:600 }}>{d.count} {d.count===1?'entry':'entries'}</div>
                  </div>
                  <div style={{ fontFamily:'var(--font-ui)', fontWeight:700, fontSize:15 }}>{c ? fmtMoney(d.native, c).text : '—'}</div>
                </div>
              );
            })}
          </div>
          {a.single ? null : (
            <p className="faint" style={{ fontSize:11.5, marginTop:14, fontWeight:600, lineHeight:1.5 }}>
              Totals above convert mixed currencies to ฿THB using your rates.
            </p>
          )}
        </div>
      </div>

      {/* recent */}
      <div className="section-head"><h3>Recent</h3><button className="btn btn-soft btn-sm" onClick={onAdd}>＋ Add</button></div>
      <div className="entry-list">
        {project.entries.slice(0,5).map(e => <EntryRow key={e.id} entry={e} />)}
      </div>
    </div>
  );
}

/* ============ ENTRY ROW ============ */
let _openEntry = null; // set by App
function EntryRow({ entry }) {
  const t = Store.type(entry.typeId), c = Store.currency(entry.currencyId), o = Store.owner(entry.owner);
  const m = fmtMoney(entry.value, c);
  return (
    <div className={`entry ${entry.settled ? 'settled' : ''}`} onClick={() => _openEntry && _openEntry(entry)}
         style={entry.settled ? { opacity: .58 } : null}>
      <IconBadge name={t?.icon || 'coin'} color={t?.color || '#EC6F9E'} size={42} />
      <div className="entry-body">
        <div className="entry-name" style={entry.settled ? { textDecoration:'line-through' } : null}>{entry.name}</div>
        <div className="entry-meta">
          <FlowChip flow={entry.flow} />
          {t && <><span className="dot" /><span>{t.name}</span></>}
          <span className="dot" /><Avatar owner={o} size={15} /><span>{o?.name}</span>
          <span className="dot" /><span>{relDate(entry.date)}</span>
          {entry.note && <><span className="dot" /><span title={entry.note} style={{ maxWidth:160, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>“{entry.note}”</span></>}
        </div>
      </div>
      <div className="entry-amt">
        <div className={`amt ${m.blank ? 'blank' : ''}`} style={!m.blank && c ? { color: shade(c.color,-10) } : null}>{m.text}</div>
      </div>
    </div>
  );
}

/* ============ ENTRIES VIEW ============ */
function EntriesView({ project, onAdd, toast }) {
  const S = useStore().get();
  const [q, setQ] = useS3('');
  const [fOwner, setFOwner] = useS3('all');
  const [fFlow, setFFlow] = useS3('all');

  let list = project.entries;
  if (q.trim()) { const s = q.toLowerCase(); list = list.filter(e => (e.name+e.note).toLowerCase().includes(s)); }
  if (fOwner !== 'all') list = list.filter(e => e.owner === fOwner);
  if (fFlow !== 'all') list = list.filter(e => e.flow === fFlow);

  if (project.entries.length === 0) {
    return <Empty icon={<Icon name="wallet" size={40} color="var(--rose)" />} title="No entries yet 🌸"
      sub="Add costs, notes, or shared coins. Everything saves automatically." 
      action={<button className="btn btn-primary" onClick={onAdd}>＋ Add first entry</button>} />;
  }

  return (
    <div className="fade-in">
      <div style={{ display:'flex', gap:10, marginBottom:16, flexWrap:'wrap', alignItems:'center' }}>
        <div style={{ position:'relative', flex:1, minWidth:180 }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--ink-faint)" strokeWidth="2.2" strokeLinecap="round" style={{ position:'absolute', left:14, top:'50%', transform:'translateY(-50%)' }}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg>
          <input className="input" style={{ paddingLeft:38 }} placeholder="Search entries…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <select className="select" style={{ width:'auto' }} value={fOwner} onChange={e => setFOwner(e.target.value)}>
          <option value="all">Everyone</option>
          {S.owners.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
        </select>
        <select className="select" style={{ width:'auto' }} value={fFlow} onChange={e => setFFlow(e.target.value)}>
          <option value="all">All kinds</option>
          <option value="spent">Spent</option>
          <option value="have">Have</option>
          <option value="received">Got</option>
        </select>
        <button className="btn btn-primary" onClick={onAdd}>＋ Add</button>
      </div>
      {list.length === 0 ? <p className="muted" style={{ textAlign:'center', padding:'30px' }}>Nothing matches that filter 🍵</p> : (
        <div className="entry-list">{list.map(e => <EntryRow key={e.id} entry={e} />)}</div>
      )}
    </div>
  );
}

Object.assign(window, { Dashboard, EntriesView, EntryRow, setEntryOpener: (fn) => { _openEntry = fn; } });
