/* global React, CRYPTOLIVE_DATA, Coin, fmtPrice, fmtPct, fmtKRW, Icon */

function daysBetween(iso) {
  const a = new Date(iso);
  const b = new Date();
  return Math.max(0, Math.round((b - a) / 86400000));
}

function HoldingPriceChart({ asset, buyDate, costBasis }) {
  const days = Math.max(7, Math.min(daysBetween(buyDate) || 30, 365));
  const n = Math.min(60, Math.max(14, days));
  const w = 800, h = 240;
  // Synthesize a price walk from buy price to current price across `days`
  const data = React.useMemo(() => {
    const arr = [];
    const start = costBasis;
    const end = asset.tokenPrice;
    let p = start;
    for (let i = 0; i < n; i++) {
      const drift = (end - p) / (n - i || 1);
      const noise = (Math.sin(i * 0.9 + asset.id.length) + Math.cos(i * 1.4)) * end * 0.014;
      p = p + drift + noise;
      arr.push(p);
    }
    arr[arr.length - 1] = end;
    arr[0] = start;
    return arr;
  }, [asset.id, asset.tokenPrice, costBasis, n]);

  const min = Math.min(...data, costBasis);
  const max = Math.max(...data, costBasis);
  const span = max - min || 1;
  const yOf = (v) => h - ((v - min) / span) * (h - 40) - 20;
  const stepX = w / (data.length - 1);
  const pts = data.map((v, i) => [i * stepX, yOf(v)]);
  const d = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const dFill = d + ` L${w},${h} L0,${h} Z`;
  const up = asset.tokenPrice >= costBasis;
  const color = up ? 'var(--up)' : 'var(--down)';
  const costY = yOf(costBasis);
  const lastPt = pts[pts.length - 1];

  return (
    <div style={{ position: 'relative' }}>
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: h, display: 'block' }}>
        <defs>
          <linearGradient id="hpcg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.22" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        {/* Cost basis line */}
        <line x1="0" x2={w} y1={costY} y2={costY} stroke="var(--fg-3)" strokeWidth="1" strokeDasharray="4 4" opacity="0.7" />
        <path d={dFill} fill="url(#hpcg)" />
        <path d={d} fill="none" stroke={color} strokeWidth="2.2" strokeLinejoin="round" strokeLinecap="round" />
        {/* Buy point */}
        <circle cx="0" cy={yOf(costBasis)} r="5" fill="var(--bg-card)" stroke="var(--fg-2)" strokeWidth="2" />
        {/* Current point */}
        <circle cx={lastPt[0]} cy={lastPt[1]} r="5" fill={color} stroke="var(--bg-card)" strokeWidth="2" />
      </svg>
      <div style={{ position: 'absolute', left: 8, top: yOf(costBasis) - 22, fontSize: 11, color: 'var(--fg-2)', background: 'var(--bg-card)', padding: '2px 6px', borderRadius: 4, border: '1px solid var(--line-soft)' }}>
        취득가 ${fmtPrice(costBasis)}
      </div>
    </div>
  );
}

function HoldingDetailScreen({ holding, goto }) {
  const asset = CRYPTOLIVE_DATA.assets().find(a => a.id === holding.id);
  if (!asset) return <div className="container page">보유 종목을 찾을 수 없습니다.</div>;

  const qty = holding.qty;
  const cost = holding.cost;
  const buyDate = holding.buyDate || new Date().toISOString().slice(0, 10);
  const venue = holding.venue || asset.venues?.[0]?.name || '-';
  const value = qty * asset.tokenPrice;
  const costBasis = qty * cost;
  const pnl = value - costBasis;
  const pnlPct = (pnl / costBasis) * 100;
  const up = pnl >= 0;
  const heldDays = daysBetween(buyDate);
  const annualized = heldDays > 0 ? (Math.pow(value / costBasis, 365 / heldDays) - 1) * 100 : pnlPct;

  return (
    <div className="container page" data-screen-label={`Holding-${asset.symbol}`}>
      <button className="btn btn--ghost btn--sm" onClick={() => goto({ tab: 'portfolio' })} style={{ marginBottom: 12 }}>
        ← 포트폴리오로
      </button>

      {/* Header */}
      <div className="card card-pad-lg" style={{ marginBottom: 16, background: 'var(--hero-grad)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
          <Coin id={asset.id} symbol={asset.symbol} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 22, letterSpacing: '-0.01em' }}>{asset.symbol}</div>
            <div className="t-meta">{asset.name} · 내 포지션</div>
          </div>
          <button className="btn btn--sm" onClick={() => goto({ tab: 'detail', assetId: asset.id })}>
            마켓 상세 →
          </button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 16 }}>
          <div>
            <div className="t-meta">평가금액</div>
            <div className="t-display t-num" style={{ fontSize: 28, marginTop: 2 }}>${value.toLocaleString('en-US', { maximumFractionDigits: 2 })}</div>
            <div className="t-meta" style={{ marginTop: 2 }}>≈ {fmtKRW(value)}</div>
          </div>
          <div>
            <div className="t-meta">평가손익</div>
            <div className={`t-h2 t-num ${up ? 'c-up' : 'c-down'}`} style={{ marginTop: 2 }}>
              {up ? '+' : ''}${pnl.toFixed(2)}
            </div>
            <div className={`t-num ${up ? 'c-up' : 'c-down'}`} style={{ fontSize: 13, fontWeight: 600 }}>{fmtPct(pnlPct)}</div>
          </div>
          <div>
            <div className="t-meta">취득가액</div>
            <div className="t-h2 t-num" style={{ marginTop: 2 }}>${costBasis.toLocaleString('en-US', { maximumFractionDigits: 2 })}</div>
            <div className="t-meta" style={{ marginTop: 2 }}>{qty.toLocaleString()} 토큰 × ${fmtPrice(cost)}</div>
          </div>
        </div>
      </div>

      {/* Chart */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
          <div>
            <div style={{ fontWeight: 700 }}>매수일 이후 추이</div>
            <div className="t-meta" style={{ marginTop: 2 }}>취득가 ${fmtPrice(cost)} → 현재 ${fmtPrice(asset.tokenPrice)}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="t-meta">보유 기간</div>
            <div className="t-h3 t-num">{heldDays}일</div>
          </div>
        </div>
        <HoldingPriceChart asset={asset} buyDate={buyDate} costBasis={cost} />
      </div>

      {/* Position facts */}
      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="card">
          <div style={{ fontWeight: 700, marginBottom: 12 }}>포지션 정보</div>
          {[
            ['매수 일자', buyDate.replace(/-/g, '.')],
            ['보유 수량', `${qty.toLocaleString()} ${asset.symbol}`],
            ['평균 매수가', `$${fmtPrice(cost)}`],
            ['현재가', `$${fmtPrice(asset.tokenPrice)}`],
            ['구매 거래소', venue],
            ['자산 분류', `${asset.class} · ${asset.sector}`],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--line-soft)' }}>
              <span className="t-meta">{k}</span>
              <span className="t-num" style={{ fontWeight: 600 }}>{v}</span>
            </div>
          ))}
        </div>

        <div className="card">
          <div style={{ fontWeight: 700, marginBottom: 12 }}>수익률 분석</div>
          {[
            ['누적 수익률', fmtPct(pnlPct), up ? 'c-up' : 'c-down'],
            ['연환산 수익률', fmtPct(annualized), annualized >= 0 ? 'c-up' : 'c-down'],
            ['손익 (USD)', `${up ? '+' : ''}$${pnl.toFixed(2)}`, up ? 'c-up' : 'c-down'],
            ['손익 (KRW)', `${up ? '+' : ''}${fmtKRW(pnl)}`, up ? 'c-up' : 'c-down'],
            ['24시간 변동', fmtPct(asset.change24h), asset.change24h >= 0 ? 'c-up' : 'c-down'],
            ['보유 기간', `${heldDays}일`, ''],
          ].map(([k, v, c]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--line-soft)' }}>
              <span className="t-meta">{k}</span>
              <span className={`t-num ${c}`} style={{ fontWeight: 600 }}>{v}</span>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

window.HoldingDetailScreen = HoldingDetailScreen;
