// terminal-portfolio.jsx — Portfolio screen + P/L Calendar.
// Templated from screenshots 3 & 4: My Assets · Assets Analysis · P/L Analysis · IPO P/L.
// Calendar is the showpiece — daily $ and % color-coded.

function PortfolioScreen({ onOpenDetail }) {
  const [view, setView] = React.useState('assets');     // assets | pnl | ipo
  const [pnlScope, setPnlScope] = React.useState('month');

  const holdings = allHoldings();
  const totalValue = holdings.reduce((s, h) => s + h.value, 0);
  const totalCost  = holdings.reduce((s, h) => s + h.costBasis, 0);
  const dayPnl     = +(totalValue * 0.0042).toFixed(2);  // mock 0.42% day
  const dayPnlPct  = 0.42;
  const totalPnl   = +(totalValue - totalCost).toFixed(2);
  const totalPnlPct = +(((totalValue - totalCost) / totalCost) * 100).toFixed(2);

  const month = new Date().getUTCMonth() + 1;
  const year = new Date().getUTCFullYear();
  const cal  = pnlCalendar(year, month);
  const sum  = pnlMonthSummary(cal);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto' }} className="tx-scroll">
      <TopBar title="Portfolio" subtitle="Live · synced 14:02 ET"
        right={<button style={{ width: 32, height: 32, borderRadius: 16, color: TM.muted }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M5 12v7a1 1 0 001 1h12a1 1 0 001-1v-7M12 3v12M8 7l4-4 4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>}/>

      {/* HERO — total value + day P/L */}
      <div style={{
        padding: '20px 16px',
        background: `linear-gradient(180deg, ${TM.cyanSoft}, transparent)`,
        borderBottom: `1px solid ${TM.border}`,
      }}>
        <div style={{ fontFamily: GE, fontSize: 12, color: TM.muted, letterSpacing: -0.05 }}>
          Total value · USD
        </div>
        <div style={{
          fontFamily: GM, fontSize: 36, fontWeight: 600,
          color: TM.text, letterSpacing: -0.8, marginTop: 6, lineHeight: 1,
        }}>
          ${totalValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
        </div>
        <div style={{
          marginTop: 10, display: 'flex', gap: 12, flexWrap: 'wrap',
          fontFamily: GM, fontSize: 12,
        }}>
          <span style={{ color: dayPnl >= 0 ? TM.green : TM.red }}>
            Today {dayPnl >= 0 ? '+' : ''}${Math.abs(dayPnl).toFixed(2)} ({dayPnl >= 0 ? '+' : ''}{dayPnlPct}%)
          </span>
          <span style={{ color: TM.muted }}>·</span>
          <span style={{ color: totalPnl >= 0 ? TM.green : TM.red }}>
            All-time {totalPnl >= 0 ? '+' : ''}${Math.abs(totalPnl).toFixed(2)} ({totalPnl >= 0 ? '+' : ''}{totalPnlPct}%)
          </span>
        </div>
      </div>

      {/* View tabs */}
      <div style={{
        display: 'flex', gap: 22, padding: '14px 16px 8px',
        borderBottom: `1px solid ${TM.border}`, overflowX: 'auto',
      }} className="tx-scroll">
        {[
          { key: 'assets', label: 'Assets Analysis' },
          { key: 'pnl',    label: 'P/L Analysis' },
          { key: 'ipo',    label: 'IPO P/L' },
        ].map(v => {
          const active = view === v.key;
          return (
            <button key={v.key} onClick={() => setView(v.key)} style={{
              padding: '4px 0 10px',
              fontFamily: GE, fontSize: 15, fontWeight: active ? 600 : 400,
              color: active ? TM.text : TM.muted,
              borderBottom: active ? `2px solid ${TM.orange}` : '2px solid transparent',
              whiteSpace: 'nowrap', letterSpacing: -0.2,
            }}>{v.label}</button>
          );
        })}
      </div>

      {view === 'assets' && <AssetsView holdings={holdings} onOpenDetail={onOpenDetail}/>}
      {view === 'pnl' && (
        <PnlView year={year} month={month} cal={cal} sum={sum} scope={pnlScope} onScope={setPnlScope}/>
      )}
      {view === 'ipo' && <IpoView/>}
    </div>
  );
}

// ── Assets Analysis view ─────────────────────────────────────
function AssetsView({ holdings, onOpenDetail }) {
  const total = holdings.reduce((s, h) => s + h.value, 0);

  return (
    <div>
      {/* Allocation donut summary */}
      <div style={{
        padding: '20px 16px 12px', display: 'flex', gap: 16, alignItems: 'center',
      }}>
        <AllocationDonut holdings={holdings} total={total} size={120}/>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
          {holdings.slice(0, 4).map((h, i) => {
            const c = [TM.cyan, TM.green, TM.amber, TM.violet, TM.red, TM.orange][i % 6];
            return (
              <div key={h.sym} style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: GE, fontSize: 12.5 }}>
                <span style={{ width: 8, height: 8, borderRadius: 4, background: c }}/>
                <span style={{ color: TM.text, fontWeight: 500 }}>{h.sym}</span>
                <span style={{ color: TM.muted, marginLeft: 'auto' }}>{((h.value / total) * 100).toFixed(2)}%</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Holdings list */}
      <SectionHeader title="Holdings" action={`${holdings.length} positions`}/>
      {holdings.map(h => (
        <HoldingRow key={h.sym} h={h} onClick={() => onOpenDetail(h.sym)}/>
      ))}
    </div>
  );
}

function HoldingRow({ h, onClick }) {
  const color = h.pnl >= 0 ? TM.green : TM.red;
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      display: 'grid', gridTemplateColumns: '36px 1fr 110px', gap: 12, alignItems: 'center',
      padding: '14px 16px', borderBottom: `1px solid ${TM.border}`,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 18,
        background: h.up ? TM.greenSoft : TM.redSoft,
        border: `1px solid ${color}`, color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: GM, fontSize: 10, fontWeight: 600,
      }}>{h.sym.slice(0, 3)}</div>
      <div>
        <div style={{ fontFamily: GE, fontSize: 14.5, fontWeight: 600, color: TM.text, letterSpacing: -0.2 }}>
          {h.sym}
          <span style={{ color: TM.muted, fontWeight: 400, marginLeft: 8, fontSize: 12 }}>
            {h.shares} {h.shares < 10 ? '' : 'sh'}
          </span>
        </div>
        <div style={{ fontFamily: GE, fontSize: 12, color: TM.muted, marginTop: 2 }}>
          @ ${h.cost.toFixed(2)} · now ${h.price.toFixed(2)}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: GM, fontSize: 14, color: TM.text, fontWeight: 600, letterSpacing: -0.1 }}>
          ${h.value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
        </div>
        <div style={{ fontFamily: GM, fontSize: 11, color, marginTop: 2 }}>
          {h.pnl >= 0 ? '+' : ''}{h.pnl.toFixed(2)} ({h.pnl >= 0 ? '+' : ''}{h.pnlPct}%)
        </div>
      </div>
    </button>
  );
}

function AllocationDonut({ holdings, total, size = 120 }) {
  const r = size / 2;
  const stroke = 14;
  const inner = r - stroke / 2;
  const circ = 2 * Math.PI * inner;
  let offset = 0;
  const colors = [TM.cyan, TM.green, TM.amber, TM.violet, TM.red, TM.orange];
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={r} cy={r} r={inner} fill="none"
        stroke={TM.surfaceHi} strokeWidth={stroke}/>
      {holdings.map((h, i) => {
        const frac = h.value / total;
        const len = circ * frac;
        const arc = (
          <circle key={h.sym}
            cx={r} cy={r} r={inner} fill="none"
            stroke={colors[i % colors.length]} strokeWidth={stroke}
            strokeDasharray={`${len} ${circ}`}
            strokeDashoffset={-offset}
            transform={`rotate(-90 ${r} ${r})`}/>
        );
        offset += len;
        return arc;
      })}
      <text x={r} y={r - 2} fill={TM.muted} fontSize="10"
            textAnchor="middle" style={{ fontFamily: GM, letterSpacing: 0.4 }}>NET</text>
      <text x={r} y={r + 12} fill={TM.text} fontSize="14" fontWeight="600"
            textAnchor="middle" style={{ fontFamily: GM, letterSpacing: -0.2 }}>
        ${(total / 1000).toFixed(1)}k
      </text>
    </svg>
  );
}

// ── P/L Analysis view (with the calendar) ───────────────────
function PnlView({ year, month, cal, sum, scope, onScope }) {
  const [openDay, setOpenDay] = React.useState(null);
  const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];

  return (
    <div>
      <div style={{ padding: '20px 16px 0' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        }}>
          <div>
            <h3 style={{ margin: 0, fontFamily: GE, fontSize: 22, fontWeight: 600, color: TM.text, letterSpacing: -0.4 }}>
              P/L Calendar
              <span style={{ color: TM.muted, marginLeft: 6, fontSize: 13 }}>i</span>
            </h3>
          </div>
          <Segmented value={scope} onChange={onScope} options={[
            { key: 'month', label: 'Month' },
            { key: 'year',  label: 'Year' },
          ]}/>
        </div>
        <div style={{
          marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 6,
        }}>
          <span style={{ fontFamily: GE, fontSize: 14, fontWeight: 500, color: TM.text }}>
            {MONTHS[month - 1]} {year}
          </span>
          <span style={{ color: TM.muted, fontSize: 12 }}>▾</span>
        </div>
      </div>

      {/* Month summary */}
      <div style={{
        margin: '12px 16px 6px', padding: '14px 16px',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
        display: 'flex', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted }}>{MONTHS[month - 1]} P/L · USD</div>
          <div style={{
            fontFamily: GM, fontSize: 22, fontWeight: 600,
            color: sum.dollars >= 0 ? TM.green : TM.red, letterSpacing: -0.4, marginTop: 4,
          }}>
            {sum.dollars >= 0 ? '+' : ''}${Math.abs(sum.dollars).toFixed(2)}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted }}>Return</div>
          <div style={{
            fontFamily: GM, fontSize: 22, fontWeight: 600,
            color: sum.pct >= 0 ? TM.green : TM.red, letterSpacing: -0.4, marginTop: 4,
          }}>
            {sum.pct >= 0 ? '+' : ''}{sum.pct}%
          </div>
        </div>
      </div>

      {/* Calendar grid */}
      <CalendarGrid days={cal} onPickDay={setOpenDay}/>

      {/* Bottom sheet — Cumulative P/L Details (templated) */}
      <CumulativePnlDetails sum={sum} cal={cal}/>

      {/* Day detail modal */}
      {openDay && (
        <DayDetailSheet day={openDay} onClose={() => setOpenDay(null)}/>
      )}
    </div>
  );
}

function CalendarGrid({ days, onPickDay }) {
  if (!days.length) return null;
  const firstDow = days[0].date.getUTCDay();
  // pad with empty leading cells
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push({ blank: true });
  cells.push(...days);
  const DOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  return (
    <div style={{ padding: '4px 12px 4px' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 0,
        fontFamily: GE, fontSize: 11, color: TM.muted, padding: '8px 0',
        borderBottom: `1px solid ${TM.border}`, textAlign: 'center',
      }}>
        {DOW.map(d => <div key={d} style={{ padding: '2px 0' }}>{d}</div>)}
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 0,
      }}>
        {cells.map((c, i) => c.blank ? (
          <div key={'blank-' + i} style={{ minHeight: 56, borderBottom: `1px solid ${TM.border}` }}/>
        ) : (
          <button key={c.d} onClick={() => !c.isWeekend && c.dollars !== 0 && onPickDay(c)} style={{
            minHeight: 56, padding: '4px 2px',
            borderBottom: `1px solid ${TM.border}`,
            borderRight: (i + 1) % 7 === 0 ? 'none' : `1px solid ${TM.border}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            cursor: c.isWeekend || c.dollars === 0 ? 'default' : 'pointer',
          }}>
            <div style={{ fontFamily: GE, fontSize: 12, color: TM.text, fontWeight: 500 }}>{c.d}</div>
            {!c.isWeekend && c.dollars !== 0 && (
              <>
                <div style={{
                  fontFamily: GM, fontSize: 10, fontWeight: 600,
                  color: c.dollars >= 0 ? TM.green : TM.red, letterSpacing: -0.1,
                }}>
                  {c.dollars >= 0 ? '+' : ''}{c.dollars.toFixed(2)}
                </div>
                <div style={{
                  fontFamily: GM, fontSize: 9.5,
                  color: c.pct >= 0 ? TM.green : TM.red,
                }}>
                  {c.pct >= 0 ? '+' : ''}{c.pct.toFixed(2)}%
                </div>
              </>
            )}
          </button>
        ))}
      </div>
    </div>
  );
}

function CumulativePnlDetails({ sum, cal }) {
  const ending = 116.71;
  const beginning = 3665.64;
  const netInflow = -245;
  const cumPnl = +(ending - beginning - netInflow).toFixed(2);
  return (
    <div style={{ padding: '20px 16px 24px' }}>
      <h3 style={{ margin: 0, fontFamily: GE, fontSize: 22, fontWeight: 600, color: TM.text, letterSpacing: -0.4 }}>
        Cumulative P/L Details
      </h3>
      <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 0 }}>
        {[
          ['Ending Assets',           ending.toFixed(2),       TM.text],
          ['Beginning Assets',        beginning.toLocaleString(undefined, { minimumFractionDigits: 2 }), TM.text],
          ['Net Inflow',              netInflow.toFixed(2),    TM.text],
          ['  Cash Deposit / Withdrawal', netInflow.toFixed(2), TM.muted, true],
          ['  Stock Transfer',        '0.00',                  TM.muted, true],
          ['  Other',                 '0.00',                  TM.muted, true],
          ['Currency Conv. Difference','0.00',                 TM.text],
        ].map(([k, v, c, indent], i) => (
          <div key={k} style={{
            display: 'flex', justifyContent: 'space-between',
            padding: '12px 0', borderTop: i === 0 ? 'none' : `1px solid ${TM.border}`,
            paddingLeft: indent ? 14 : 0,
          }}>
            <span style={{ fontFamily: GE, fontSize: 14, color: c, fontWeight: indent ? 400 : 500, letterSpacing: -0.1 }}>{k}</span>
            <span style={{ fontFamily: GM, fontSize: 14, color: c, letterSpacing: 0.1 }}>{v}</span>
          </div>
        ))}
        <div style={{
          marginTop: 6, paddingTop: 12, borderTop: `1px solid ${TM.border}`,
          display: 'flex', justifyContent: 'space-between',
        }}>
          <span style={{ fontFamily: GE, fontSize: 15, color: TM.text, fontWeight: 600 }}>Cumulative P/L</span>
          <span style={{
            fontFamily: GM, fontSize: 16, fontWeight: 600,
            color: cumPnl >= 0 ? TM.green : TM.red, letterSpacing: -0.1,
          }}>
            {cumPnl >= 0 ? '+' : ''}{cumPnl.toFixed(2)}
          </span>
        </div>
        <div style={{
          marginTop: 8, fontFamily: GE, fontSize: 11.5, color: TM.muted, lineHeight: 1.5,
        }}>
          Cumulative P/L = Ending Assets − Beginning Assets − Net Inflow − Currency Conversion Difference
        </div>
      </div>
    </div>
  );
}

function DayDetailSheet({ day, onClose }) {
  const dateLabel = day.date.toUTCString().slice(0, 16);
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 100,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 430,
        background: TM.surface, color: TM.text,
        borderTop: `1px solid ${TM.borderHi}`,
        borderRadius: '24px 24px 0 0',
        padding: '14px 16px 28px',
        animation: 'fade-in .25s ease both',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}>
          <span style={{ width: 36, height: 4, background: TM.borderHi, borderRadius: 2 }}/>
        </div>
        <h3 style={{ margin: 0, fontFamily: GE, fontSize: 18, fontWeight: 600, color: TM.text }}>{dateLabel}</h3>
        <div style={{
          marginTop: 8, fontFamily: GM, fontSize: 24, fontWeight: 600,
          color: day.dollars >= 0 ? TM.green : TM.red, letterSpacing: -0.4,
        }}>
          {day.dollars >= 0 ? '+' : ''}${Math.abs(day.dollars).toFixed(2)} ({day.pct >= 0 ? '+' : ''}{day.pct}%)
        </div>
        <div style={{ marginTop: 16, padding: '12px 14px', background: TM.cyanSoft, border: `1px solid rgba(35,200,233,0.30)`, borderRadius: 8 }}>
          <div style={{ fontFamily: GM, fontSize: 10, color: TM.cyan, letterSpacing: 1.2, fontWeight: 600 }}>RECEIPTS THIS DAY</div>
          <div style={{ marginTop: 6, fontFamily: GE, fontSize: 14, color: TM.text, letterSpacing: -0.1 }}>
            Tap Receipts tab to inspect every trade that hit this day, with compute_proof + Base block.
          </div>
        </div>
      </div>
    </div>
  );
}

function IpoView() {
  return (
    <div style={{ padding: '40px 24px', textAlign: 'center' }}>
      <div style={{
        width: 56, height: 56, borderRadius: 28, margin: '0 auto 12px',
        border: `1px solid ${TM.border}`, background: TM.surfaceHi,
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: TM.muted,
      }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M3 17l6-6 4 4 8-8" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          <path d="M14 7h7v7" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
      <div style={{ fontFamily: GE, fontSize: 15, color: TM.text, fontWeight: 500 }}>No IPO allocations</div>
      <div style={{ marginTop: 6, fontFamily: GE, fontSize: 13, color: TM.muted, lineHeight: 1.5 }}>
        IPO P/L tracking activates the moment your first allocation prices. Subscribe to upcoming IPOs from the Markets tab.
      </div>
    </div>
  );
}

Object.assign(window, { PortfolioScreen });
