// FundScreens.jsx — all the fund screens

const { useState, useMemo, useEffect } = React;

// ─── Shared UI ────────────────────────────────────────────────
function ChartToggle({ value, onChange }) {
  const opts = [
    { k: 'area', label: 'Linje' },
    { k: 'bar', label: 'Søyler' },
  ];
  return (
    <div style={{ display: 'flex', gap: 4, padding: 3, background: BB.surface2, borderRadius: 999 }}>
      {opts.map(o => (
        <button key={o.k} onClick={() => onChange(o.k)} style={{
          flex: 1, padding: '6px 12px', borderRadius: 999, border: 'none',
          background: value === o.k ? BB.fg : 'transparent',
          color: value === o.k ? BB.bg : BB.fg2,
          fontSize: 12, fontWeight: 600, cursor: 'pointer',
          fontFamily: 'inherit',
        }}>{o.label}</button>
      ))}
    </div>
  );
}

function PeriodTabs({ value, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 2, padding: 3, background: BB.surface2, borderRadius: 999 }}>
      {PERIODS.map(p => (
        <button key={p} onClick={() => onChange(p)} style={{
          flex: 1, padding: '7px 0', borderRadius: 999, border: 'none',
          background: value === p ? BB.fg : 'transparent',
          color: value === p ? BB.bg : BB.fg2,
          fontSize: 12, fontWeight: 600, cursor: 'pointer',
          fontFamily: 'inherit',
        }}>{p}</button>
      ))}
    </div>
  );
}

function RiskDots({ risk = 6, max = 7 }) {
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {Array.from({ length: max }).map((_, i) => (
        <div key={i} style={{
          width: 6, height: 6, borderRadius: 999,
          background: i < risk ? (risk >= 5 ? BB.amber : BB.green) : 'rgba(255,255,255,0.12)',
        }}/>
      ))}
    </div>
  );
}

function Stars({ n }) {
  return (
    <div style={{ display: 'flex', gap: 1 }}>
      {[0,1,2,3,4].map(i => (
        <svg key={i} width="12" height="12" viewBox="0 0 24 24" fill={i < n ? BB.amber : 'rgba(255,255,255,0.15)'}>
          <path d="M12 2l3 7h7l-5.5 4.5L18 21l-6-4.5L6 21l1.5-7.5L2 9h7z"/>
        </svg>
      ))}
    </div>
  );
}

function PrimaryButton({ children, onClick, style = {}, variant = 'royal' }) {
  const bg = variant === 'royal' ? BB.royal : (variant === 'bulder' ? BB.pink : BB.fg);
  const fg = variant === 'ghost' ? BB.fg : '#fff';
  if (variant === 'ghost') return (
    <button onClick={onClick} style={{
      flex: 1, padding: '14px 18px', borderRadius: 999,
      background: 'rgba(255,255,255,0.08)', color: BB.fg,
      border: 'none', fontSize: 16, fontWeight: 500,
      fontFamily: 'inherit', cursor: 'pointer', ...style,
    }}>{children}</button>
  );
  return (
    <button onClick={onClick} style={{
      flex: 1, padding: '14px 18px', borderRadius: 999,
      background: bg, color: fg, border: 'none',
      fontSize: 16, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
      ...style,
    }}>{children}</button>
  );
}

function ScreenHeader({ title, onBack, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '60px 16px 14px' }}>
      <button onClick={onBack} style={{
        width: 36, height: 36, borderRadius: 999, border: 'none',
        background: 'rgba(255,255,255,0.08)', color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
      }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M15 18l-6-6 6-6"/>
        </svg>
      </button>
      <div style={{ flex: 1, fontSize: 17, fontWeight: 600, color: BB.fg, textAlign: 'center' }}>{title}</div>
      <div style={{ width: 36, display: 'flex', justifyContent: 'flex-end' }}>{right}</div>
    </div>
  );
}

function FundMark({ fund, size = 44 }) {
  // use the Bulder staircase mark in fund's color
  return (
    <div style={{
      width: size, height: size, borderRadius: 10, flexShrink: 0,
      background: fund.color, display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative', overflow: 'hidden',
    }}>
      <svg width={size * 0.58} height={size * 0.58} viewBox="0 0 64 64" style={{ opacity: 0.95 }}>
        <path fillRule="evenodd" clipRule="evenodd" d="M32.11 9L1 40.11V55.66L39.90 16.78L47.66 24.55L32.11 40.11H47.66L63.22 24.55L47.66 9H32.11ZM47.66 40.11L32.11 55.66H47.66L63.22 40.11H47.66Z" fill="#fff"/>
      </svg>
    </div>
  );
}

// ─── OVERSIKT: the fund overview ──────────────────────────────
function OversiktScreen({ nav, chartStyle, cardLayout, setChartStyle, setCardLayout }) {
  const [period, setPeriod] = useState('1Å');
  const [hoverIdx, setHoverIdx] = useState(null);
  const [hideAmounts, setHideAmounts] = useState(false);

  const owned = getOwnedFunds();
  const totalValue = getTotalValue();
  const totalCost = getTotalCost();
  const totalGain = getTotalGain();
  const totalGainPct = getTotalGainPct();

  const series = useMemo(() => getPortfolioSeries(period), [period]);
  const shownIdx = hoverIdx ?? series.length - 1;
  const shownVal = series[shownIdx];
  const shownPct = (shownVal - series[0]) / series[0];

  // Map series % back to NOK value for tooltip
  const shownNok = totalCost * (shownVal / 100);

  const Chart = chartStyle === 'bar' ? BarChart : AreaChart;

  const formatAmount = v => hideAmounts ? '•••••' : fmtNok(v);

  return (
    <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', padding: '60px 16px 8px', gap: 10 }}>
        <button onClick={() => nav('back')} style={{ width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.08)', color: '#fff', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
        </button>
        <div style={{ flex: 1, fontSize: 26, fontWeight: 700, color: BB.fg, letterSpacing: '-0.02em' }}>Fond</div>
        <button onClick={() => setHideAmounts(!hideAmounts)} style={{
          width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.08)', color: '#fff', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            {hideAmounts
              ? <><path d="M2 12s4-8 10-8 10 8 10 8-4 8-10 8S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></>
              : <><path d="M17.94 17.94A10.07 10.07 0 0112 20c-6 0-10-8-10-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c6 0 10 8 10 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></>}
          </svg>
        </button>
      </div>

      {/* Hero value */}
      <div style={{ padding: '16px 20px 8px', textAlign: 'center' }}>
        <div style={{ fontSize: 13, color: BB.fg2, marginBottom: 6, letterSpacing: '0.02em' }}>
          {hoverIdx != null ? 'Verdi ved visning' : 'Samlet verdi'}
        </div>
        <div style={{ fontSize: 56, fontWeight: 400, color: BB.fg, letterSpacing: '-0.035em', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
          {formatAmount(shownNok)}
          <span style={{ fontSize: 24, color: BB.fg2, marginLeft: 8 }}>kr</span>
        </div>
        <div style={{ marginTop: 10, display: 'flex', gap: 6, justifyContent: 'center', alignItems: 'center' }}>
          <span style={{
            fontSize: 14, fontWeight: 600,
            color: (shownNok - totalCost) >= 0 ? BB.green : BB.pink,
            fontVariantNumeric: 'tabular-nums',
          }}>
            {(shownNok - totalCost) >= 0 ? '+' : '−'}
            {formatAmount(Math.abs(shownNok - totalCost))} kr
          </span>
          <span style={{
            fontSize: 14, fontWeight: 600,
            padding: '3px 8px', borderRadius: 6,
            background: (shownPct >= 0 ? 'rgba(133,255,134,0.15)' : 'rgba(254,77,91,0.15)'),
            color: shownPct >= 0 ? BB.green : BB.pink,
            fontVariantNumeric: 'tabular-nums',
          }}>{fmtPct(shownPct, 2)}</span>
        </div>
      </div>

      {/* Chart */}
      <div style={{ padding: '16px 8px 8px' }}>
        <Chart data={series} height={180}
          onHover={setHoverIdx} activeIdx={hoverIdx}
          color={BB.green} negColor={BB.pink}/>
      </div>

      <div style={{ padding: '8px 16px 4px' }}>
        <PeriodTabs value={period} onChange={setPeriod}/>
      </div>
      <div style={{ padding: '8px 16px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
          Grafstil
        </div>
        <ChartToggle value={chartStyle} onChange={setChartStyle}/>
      </div>

      {/* Breakdown — cost vs value */}
      <div style={{ margin: '20px 16px 0', padding: '14px 16px', background: BB.surface, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>Innskutt</div>
          <div style={{ fontSize: 16, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums', marginTop: 4 }}>{formatAmount(totalCost)}</div>
        </div>
        <div style={{ width: 1, alignSelf: 'stretch', background: 'rgba(255,255,255,0.08)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>Avkastning</div>
          <div style={{ fontSize: 16, fontWeight: 500, color: BB.green, fontVariantNumeric: 'tabular-nums', marginTop: 4 }}>+{formatAmount(totalGain)}</div>
        </div>
        <div style={{ width: 1, alignSelf: 'stretch', background: 'rgba(255,255,255,0.08)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>Samlet</div>
          <div style={{ fontSize: 16, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums', marginTop: 4 }}>{formatAmount(totalValue)}</div>
        </div>
      </div>

      {/* Section: owned funds */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '28px 20px 8px' }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: BB.fg3, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          Dine fond
        </div>
        <button onClick={() => setCardLayout(cardLayout === 'detail' ? 'compact' : (cardLayout === 'compact' ? 'visual' : 'detail'))}
          style={{ border: 'none', background: 'transparent', color: BB.fg2, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' }}>
          Layout · {cardLayout === 'detail' ? 'Detalj' : cardLayout === 'compact' ? 'Kompakt' : 'Visuell'}
        </button>
      </div>

      {/* Fund cards — three layouts toggleable */}
      <div style={{ padding: '0 16px' }}>
        {owned.map(f => (
          <FundCard key={f.id} fund={f} layout={cardLayout} period={period} onClick={() => nav('detail', f.id)}/>
        ))}
      </div>

      {/* Projection teaser */}
      <div onClick={() => nav('projection')} style={{
        margin: '20px 16px 16px', padding: '16px',
        background: `linear-gradient(135deg, ${BB.royal} 0%, #0B1CB8 100%)`,
        borderRadius: 14, cursor: 'pointer', position: 'relative', overflow: 'hidden',
      }}>
        <svg style={{ position: 'absolute', right: -10, bottom: -10, opacity: 0.12 }} width="120" height="120" viewBox="0 0 64 64">
          <path fillRule="evenodd" clipRule="evenodd" d="M32.11 9L1 40.11V55.66L39.90 16.78L47.66 24.55L32.11 40.11H47.66L63.22 24.55L47.66 9H32.11ZM47.66 40.11L32.11 55.66H47.66L63.22 40.11H47.66Z" fill="#fff"/>
        </svg>
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.7)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Hva blir det til?</div>
          <div style={{ fontSize: 20, fontWeight: 600, color: '#fff', marginTop: 6, letterSpacing: '-0.01em' }}>Regn ut over 10 år</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.8)', marginTop: 4 }}>Se hva sparingen din kan bli</div>
        </div>
      </div>

      {/* Explore more */}
      <div onClick={() => nav('utforsk')} style={{
        margin: '0 16px 16px', padding: '16px', background: BB.surface, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
      }}>
        <div style={{ width: 42, height: 42, borderRadius: 10, background: 'rgba(9,38,214,0.2)',
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={BB.royal} strokeWidth="2.2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: BB.fg }}>Utforsk fond</div>
          <div style={{ fontSize: 13, color: BB.fg3, marginTop: 2 }}>Alle Bulders indeksfond</div>
        </div>
        <span style={{ color: BB.pink, fontSize: 20 }}>›</span>
      </div>
    </div>
  );
}

// ─── Fund card — three layout variants ────────────────────────
function FundCard({ fund, layout, period, onClick }) {
  const gain = fund.owned.valueNok - fund.owned.costNok;
  const gainPct = gain / fund.owned.costNok;
  const series = fund.series[period] || fund.series['1Å'];

  if (layout === 'compact') {
    return (
      <div onClick={onClick} style={{
        padding: '12px 14px', marginBottom: 8, background: BB.surface, borderRadius: 12,
        display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
      }}>
        <FundMark fund={fund} size={32}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 500, color: BB.fg, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{fund.name}</div>
          <div style={{ fontSize: 12, color: BB.fg3, marginTop: 1, fontVariantNumeric: 'tabular-nums' }}>{fmtNok(fund.owned.valueNok)} kr</div>
        </div>
        <Sparkline data={series} width={56} height={24}/>
        <div style={{ fontSize: 13, fontWeight: 600, color: gainPct >= 0 ? BB.green : BB.pink, fontVariantNumeric: 'tabular-nums', minWidth: 52, textAlign: 'right' }}>
          {fmtPct(gainPct, 1)}
        </div>
      </div>
    );
  }

  if (layout === 'visual') {
    return (
      <div onClick={onClick} style={{
        padding: 16, marginBottom: 10, background: BB.surface, borderRadius: 14,
        cursor: 'pointer', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
          <FundMark fund={fund} size={44}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: BB.fg }}>{fund.name}</div>
            <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{fund.tagline}</div>
          </div>
        </div>
        <div style={{ margin: '0 -4px' }}>
          <AreaChart data={series} height={70} width={320} color={fund.color} negColor={BB.pink}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>{fmtNok(fund.owned.valueNok)} <span style={{ fontSize: 13, color: BB.fg2 }}>kr</span></div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: gainPct >= 0 ? BB.green : BB.pink, fontVariantNumeric: 'tabular-nums' }}>
              {gain >= 0 ? '+' : '−'}{fmtNok(Math.abs(gain))} kr · {fmtPct(gainPct, 1)}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Default 'detail'
  return (
    <div onClick={onClick} style={{
      padding: 14, marginBottom: 10, background: BB.surface, borderRadius: 12,
      cursor: 'pointer',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <FundMark fund={fund} size={40}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: BB.fg }}>{fund.name}</div>
          <div style={{ fontSize: 11, color: BB.fg3, marginTop: 2 }}>Gebyr {fmtPctNoSign(fund.fee/100, 2)} · Risiko {fund.risk}/7</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 15, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>{fmtNok(fund.owned.valueNok)}</div>
          <div style={{ fontSize: 12, fontWeight: 600, color: gainPct >= 0 ? BB.green : BB.pink, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>
            {gain >= 0 ? '+' : '−'}{fmtNok(Math.abs(gain))} · {fmtPct(gainPct, 1)}
          </div>
        </div>
      </div>
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Sparkline data={series} width={200} height={28} color={fund.color}/>
        </div>
        <div style={{ fontSize: 11, color: BB.fg3 }}>{period}</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  ChartToggle, PeriodTabs, RiskDots, Stars, PrimaryButton,
  ScreenHeader, FundMark, OversiktScreen, FundCard,
});
