// 機構估值 — 個股工作台 Tab5，獨立於企業基本面(fundamental.jsx)之外
// 前身是 fundamental.jsx 的 Section 13「機構研究」，抽出來後改為自己 fetch 資料
// （不再依賴 FundamentalApp 已經抓好的 fins/cashFlow/currentPrice）
// 版面沿用站內既有 Formosa & Co. 視覺語言（fundamental.css 已在頁面載入）：
// .fund-desc 做內文段落、.fund-verdict-tag 做評等印章，避免另立一套風格。
const { useState, useEffect } = React;

// ─── 策展 DCF：用機構研究策展的成長率/WACC/終值成長率假設 ───
// 公式與 fundamental.jsx computeFairValue 的 DCF 區塊邏輯相同，只有 g/r/tg 三個參數來源不同（策展 vs 自動推導）
function calcCuratedDCF(financials, cashFlow, currentPrice, assumptions) {
  if (!cashFlow || cashFlow.length < 4 || !financials || financials.length < 4 || !currentPrice) return null;
  const epsRows = financials.map(q => q['EPS'] ?? null).filter(v => v != null && isFinite(v) && v !== 0);
  if (!epsRows.length) return null;
  const ttmEps = epsRows.reduce((a, b) => a + b, 0) * (4 / epsRows.length);
  if (ttmEps <= 0) return null;

  const last4cf = cashFlow.slice(-4).reduce((s, q) => s + (q.FreeCF || 0), 0);
  const last4ni = financials.slice(-4).reduce((s, q) => s + (q.NetIncome || 0), 0);
  if (last4cf <= 0 || last4ni <= 0) return null;

  const fcfPerShare = last4cf * ttmEps / last4ni;
  const { stage1Growth: g, wacc: r, terminalGrowth: tg } = assumptions;
  if (r <= tg) return null; // WACC 必須大於終值成長率，否則現值公式除以負數會爆炸

  let pv = 0, cf = fcfPerShare;
  for (let i = 1; i <= 5; i++) { cf *= (1 + g); pv += cf / Math.pow(1 + r, i); }
  const tv = (cf * (1 + tg)) / (r - tg);
  pv += tv / Math.pow(1 + r, 5);

  const value = pv > 0 ? +pv.toFixed(0) : null;
  if (!value) return null;
  const upside = +(((value - currentPrice) / currentPrice) * 100).toFixed(1);
  return { value, upside };
}

// ─── 敏感度分析：同一顆 calcCuratedDCF，跑 WACC±1% × 成長率±3% 的 3x3 網格 ───
function buildSensitivityGrid(financials, cashFlow, currentPrice, base) {
  const waccSteps = [base.wacc - 0.01, base.wacc, base.wacc + 0.01];
  const growthSteps = [base.stage1Growth - 0.03, base.stage1Growth, base.stage1Growth + 0.03];
  return waccSteps.map(wacc =>
    growthSteps.map(stage1Growth =>
      calcCuratedDCF(financials, cashFlow, currentPrice, { stage1Growth, wacc, terminalGrowth: base.terminalGrowth })
    )
  );
}

// ─── 催化劑時間軸排序 key：把策展 freeform 日期字串（'2026 H2'/'2026 Q4'/'2026-2027'/'2027'/'長期'/'持續'/'不確定'）
// 跟 tw_events 的 ISO 'YYYY-MM-DD' 統一轉成可字串比較的 'YYYY-MM' 排序鍵 ───
function dateSortKey(dateStr) {
  const s = String(dateStr || '');
  let m;
  if ((m = s.match(/^\d{4}-\d{2}-\d{2}$/))) return s; // ISO 日期已可排序，原樣回傳
  if ((m = s.match(/^(\d{4})\s*Q([1-4])-Q?([1-4])$/))) { // 區間如 '2026 Q3-Q4'：取前一季（保守起見用區間起點）
    const qMap = { 1: '-02', 2: '-05', 3: '-08', 4: '-11' };
    return m[1] + qMap[m[2]];
  }
  if ((m = s.match(/^(\d{4})[\s-]?Q([1-4])$/))) {
    const qMap = { 1: '-02', 2: '-05', 3: '-08', 4: '-11' };
    return m[1] + qMap[m[2]];
  }
  if ((m = s.match(/^(\d{4})\s*H([12])$/))) {
    const hMap = { 1: '-02', 2: '-08' };
    return m[1] + hMap[m[2]];
  }
  if ((m = s.match(/^(\d{4})-(\d{4})$/))) return m[1] + '-06'; // 年份區間，取起始年年中
  if ((m = s.match(/^(\d{4})$/))) return m[1] + '-06'; // 孤立年份，取年中
  return '9999-99'; // 無法解析的 freeform（長期/持續/不確定等）一律排最後
}

// ─── 小型排版元件：子區塊標題（大字中文 + 斜體英文副標 + 底線），呼應 fundamental.css 的 sec-en 語彙 ───
function SubHead({ cn, en }) {
  return (
    <div style={{
      display:'flex', alignItems:'baseline', gap:10, marginBottom:14,
      paddingBottom:8, borderBottom:'1px solid var(--paper-line)',
    }}>
      <span style={{fontFamily:'BiauKai,標楷體,serif', fontSize:17, fontWeight:700, color:'var(--ink)', letterSpacing:'.04em'}}>{cn}</span>
      <span style={{fontFamily:'Times New Roman,serif', fontStyle:'italic', fontSize:12, color:'var(--ink-mute)', letterSpacing:'.06em'}}>{en}</span>
    </div>
  );
}

function InstitutionalSection({ code, fins, cashFlow, currentPrice, twEvents }) {
  const research = (window.INSTITUTIONAL_RESEARCH || {})[code];
  const [compsBwibbu, setCompsBwibbu] = useState({});

  useEffect(function() {
    setCompsBwibbu({});
    if (!research || !research.comps?.peerCodes?.length) return;
    let alive = true;
    fetch(`/api/stock?type=bwibbu_batch&codes=${research.comps.peerCodes.join(',')}`)
      .then(r => r.json())
      .then(d => { if (alive) setCompsBwibbu(d || {}); })
      .catch(() => {});
    return function() { alive = false; };
  }, [code]);

  if (!research) {
    return (
      <div style={{textAlign:'center', padding:'56px 0', color:'var(--ink-mute)'}}>
        <div style={{fontSize:32, marginBottom:12, opacity:.7}}>📖</div>
        <div style={{fontFamily:'BiauKai,標楷體,serif', fontSize:16}}>本檔尚未納入機構研究覆蓋</div>
        <div style={{fontSize:12.5, marginTop:6, opacity:.65}}>目前僅涵蓋精選約20檔大盤股，逐步擴充中</div>
      </div>
    );
  }

  const dcfResult = research.dcf ? calcCuratedDCF(fins, cashFlow, currentPrice, research.dcf) : null;
  const moat = (window.TECH_MOAT || {})[code];
  const ratingCls = research.rating?.tag === 'buy' ? 'cheap' : research.rating?.tag === 'avoid' ? 'expensive' : 'fair';

  return (
    <div>
      <div style={{display:'flex', alignItems:'center', gap:14, flexWrap:'wrap', marginBottom:22}}>
        <div style={{fontSize:11.5, color:'var(--ink-mute)', fontStyle:'italic'}}>
          機構研究策展更新於 {research.updated}
        </div>
        {research.rating && (
          <div className={`fund-verdict-tag ${ratingCls}`} style={{fontSize:14, padding:'5px 18px'}}>
            {research.rating.label}
          </div>
        )}
      </div>

      {/* ── 策展 DCF 估值卡 ── */}
      {research.dcf && (
        <>
          <SubHead cn="估值情境" en="Valuation Scenarios" />
          {(() => {
            const scenarios = [
              research.dcfBear && { key:'bear', letter:'B', label:'悲觀情境', cls:'bear', data:research.dcfBear, result:calcCuratedDCF(fins, cashFlow, currentPrice, research.dcfBear) },
              { key:'base', letter:'I', label:'機構研究 · 策展假設', cls:'base', data:research.dcf, result:dcfResult },
              research.dcfBull && { key:'bull', letter:'U', label:'樂觀情境', cls:'bull', data:research.dcfBull, result:calcCuratedDCF(fins, cashFlow, currentPrice, research.dcfBull) },
            ].filter(Boolean);
            const labelMap = { bear:'悲 觀 估 值', base:'機 構 研 究 估 值', bull:'樂 觀 估 值' };
            return (
              <div className="fund-valuation" style={{marginBottom:18}}>
                {scenarios.map(s => (
                  <div key={s.key} className={`fund-val-card ${s.cls}`} data-letter={s.letter}>
                    <div className="fund-val-method">{s.label}</div>
                    <div className="fund-val-label">{labelMap[s.key]}</div>
                    <div className="fund-val-price" style={{fontSize: s.result ? (scenarios.length > 1 ? 26 : 30) : 20, fontWeight:800}}>
                      {s.result ? s.result.value.toLocaleString() : '—'}
                    </div>
                    <div className={`fund-val-upside ${s.result && s.result.upside >= 0 ? 'pos' : 'neg'}`} style={{fontSize: scenarios.length > 1 ? 15 : 16, fontWeight:700}}>
                      {s.result ? `${s.result.upside >= 0 ? '↑' : '↓'} ${Math.abs(s.result.upside)}%` : '財報資料不足'}
                    </div>
                    <div className="fund-val-basis">
                      FCF成長{(s.data.stage1Growth*100).toFixed(0)}% · WACC{(s.data.wacc*100).toFixed(1)}% · 終值g={(s.data.terminalGrowth*100).toFixed(0)}%
                    </div>
                  </div>
                ))}
              </div>
            );
          })()}
          <p className="fund-desc" style={{marginBottom: (research.dcfBull || research.dcfBear) ? 12 : 24}}>{research.dcf.rationale}</p>
          {research.dcfBull && (
            <p className="fund-desc" style={{borderLeftColor:'var(--bull)', marginBottom:10}}>
              <b style={{color:'var(--bull)'}}>樂觀情境成立條件　</b>{research.dcfBull.rationale}
            </p>
          )}
          {research.dcfBear && (
            <p className="fund-desc" style={{borderLeftColor:'var(--bear)', marginBottom:24}}>
              <b style={{color:'var(--bear)'}}>悲觀情境成立條件　</b>{research.dcfBear.rationale}
            </p>
          )}

          {dcfResult && (() => {
            const grid = buildSensitivityGrid(fins, cashFlow, currentPrice, research.dcf);
            const growthCols = [research.dcf.stage1Growth-0.03, research.dcf.stage1Growth, research.dcf.stage1Growth+0.03];
            return (
              <div className="frame-card" style={{padding:'20px 22px', marginBottom:24}}>
                <SubHead cn="敏感度分析" en="Sensitivity Analysis" />
                <table style={{width:'100%', borderCollapse:'collapse', fontSize:13.5, textAlign:'center', fontVariantNumeric:'tabular-nums'}}>
                  <thead>
                    <tr>
                      <th style={{padding:'8px 10px', borderBottom:'1.5px solid var(--paper-line)', fontFamily:'Times New Roman,serif', fontStyle:'italic', fontWeight:400, color:'var(--ink-mute)', fontSize:12}}>WACC ＼ 成長率</th>
                      {growthCols.map((g, i) => (
                        <th key={i} style={{padding:'8px 10px', borderBottom:'1.5px solid var(--paper-line)', fontWeight:700}}>{(g*100).toFixed(0)}%</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {grid.map((row, ri) => (
                      <tr key={ri}>
                        <td style={{padding:'9px 10px', fontWeight:700, borderBottom:'1px solid var(--paper-line)'}}>
                          {((research.dcf.wacc + (ri-1)*0.01)*100).toFixed(1)}%
                        </td>
                        {row.map((cell, ci) => {
                          const isBase = ri===1 && ci===1;
                          return (
                            <td key={ci} style={{
                              padding:'9px 10px', borderBottom:'1px solid var(--paper-line)',
                              background: isBase ? 'var(--gold)' : 'transparent',
                              color: isBase ? 'var(--paper)' : 'var(--ink)',
                              fontWeight: isBase ? 800 : 400,
                            }}>
                              {cell ? cell.value.toLocaleString() : '—'}
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
                <div style={{fontSize:11.5, color:'var(--ink-faint)', marginTop:10, fontStyle:'italic'}}>金色格＝策展基準假設；橫向為FCF成長率±3個百分點、縱向為WACC±1個百分點</div>
              </div>
            );
          })()}
        </>
      )}

      {/* ── 質化研究報告 ── */}
      <div className="frame-card" style={{padding:'20px 22px', marginBottom:24}}>
        <SubHead cn="質化研究" en="Qualitative Research" />
        {research.thesis?.summary && (
          <div style={{marginBottom:20}}>
            <div style={{fontSize:12, color:'var(--gold-deep)', letterSpacing:'.1em', marginBottom:6, fontWeight:700}}>投資論點</div>
            <p className="fund-desc">{research.thesis.summary}</p>
          </div>
        )}
        {research.thesis?.business && (
          <div style={{marginBottom:20}}>
            <div style={{fontSize:12, color:'var(--gold-deep)', letterSpacing:'.1em', marginBottom:6, fontWeight:700}}>商業模式</div>
            <p className="fund-desc">{research.thesis.business}</p>
          </div>
        )}
        {moat && (
          <div style={{marginBottom:20}}>
            <div style={{fontSize:12, color:'var(--gold-deep)', letterSpacing:'.1em', marginBottom:6, fontWeight:700}}>競爭優勢</div>
            <p className="fund-desc">{moat.headline}（詳見「企業基本面」頁的企業護城河技術版圖）</p>
          </div>
        )}
        <div style={{fontSize:12, color:'var(--gold-deep)', letterSpacing:'.1em', marginBottom:8, fontWeight:700}}>風險因子</div>
        <div>
          {(research.thesis?.risks || []).map((r, i) => (
            <div key={i} style={{display:'flex', gap:10, marginBottom:10, alignItems:'flex-start'}}>
              <span style={{flexShrink:0, marginTop:2, fontSize:'var(--fs-nano)', color:'var(--bear)', fontWeight:700}}>⚠</span>
              <span style={{fontFamily:'BiauKai,標楷體,serif', fontSize:14, lineHeight:1.85, color:'var(--ink-soft)'}}>{r}</span>
            </div>
          ))}
        </div>
      </div>

      {/* ── 深度同業比較 ── */}
      {research.comps && (
        <div className="frame-card" style={{padding:'20px 22px', marginBottom:24}}>
          <SubHead cn="可比公司" en="Comparable Companies" />
          <p className="fund-desc" style={{marginBottom:18}}>{research.comps.rationale}</p>
          <div style={{display:'flex', gap:14, flexWrap:'wrap'}}>
            {(research.comps.peerCodes || []).map(pc => {
              const b = compsBwibbu[pc] || {};
              return (
                <div key={pc} style={{
                  padding:'12px 18px', border:'1px solid var(--paper-line)', background:'var(--paper-bright)',
                  minWidth:150,
                }}>
                  <div style={{fontFamily:'BiauKai,標楷體,serif', fontSize:14, fontWeight:700, marginBottom:6}}>{pc} {b.name || ''}</div>
                  <div style={{fontSize:12.5, color:'var(--ink-mute)', fontVariantNumeric:'tabular-nums'}}>
                    P/E {b.pe != null ? b.pe.toFixed(1) : '—'} · P/B {b.pb != null ? b.pb.toFixed(1) : '—'}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ── 催化劑時間軸（質化策展事件 + tw_events 除息/財報日期）── */}
      {(() => {
        const qual = (research.catalysts || []).map(c => ({ date: c.date, title: c.title, note: c.note, tag: null }));
        // tw_events 的除息資料是近2年歷史(不像財報日期已經只回傳未來)，「催化劑」時間軸只看未來，故過濾掉今天以前的除息記錄
        const today = new Date().toISOString().slice(0, 10);
        const divs = (twEvents?.dividends || []).filter(d => d.date >= today).map(d => ({ date: d.date, title: '除息日', note: d.amount != null ? `每股 ${d.amount} 元` : '', tag: 'D' }));
        const earns = (twEvents?.earnings || []).map(e => ({ date: e.date, title: e.label, note: '財報截止日', tag: 'E' }));
        const merged = [...qual, ...divs, ...earns].sort((a, b) => dateSortKey(a.date) < dateSortKey(b.date) ? -1 : dateSortKey(a.date) > dateSortKey(b.date) ? 1 : 0);
        if (!merged.length) return null;
        return (
          <div className="frame-card" style={{padding:'20px 22px', marginBottom:24}}>
            <SubHead cn="催化劑時間軸" en="Catalyst Timeline" />
            {merged.map((c, i) => (
              <div key={i} style={{display:'flex', gap:16, marginBottom:16, paddingBottom:16, borderBottom: i < merged.length-1 ? '1px dashed var(--paper-line)' : 'none'}}>
                <div style={{minWidth:88, fontFamily:'Times New Roman,serif', fontSize:14, color: c.tag ? 'var(--ink-mute)' : 'var(--gold-deep)', fontWeight:700}}>{c.date}</div>
                <div>
                  <div style={{fontSize:14, fontWeight:700, marginBottom:5}}>
                    {c.tag && <span style={{fontSize:'var(--fs-nano)', padding:'2px 7px', marginRight:8, background: c.tag==='D' ? 'var(--gold)' : 'var(--ink-mute)', color:'var(--paper)', letterSpacing:'.04em'}}>{c.tag==='D'?'除息':'財報'}</span>}
                    {c.title}
                  </div>
                  {c.note && <div style={{fontSize:13, color:'var(--ink-mute)', lineHeight:1.75}}>{c.note}</div>}
                </div>
              </div>
            ))}
          </div>
        );
      })()}

      {/* ── 論點追蹤 Thesis Tracker ── */}
      {research.thesisLog?.length > 0 && (
        <div className="frame-card" style={{padding:'20px 22px', marginBottom:24}}>
          <SubHead cn="論點追蹤" en="Thesis Tracker" />
          {[...research.thesisLog].reverse().map((t, i) => (
            <div key={i} style={{paddingLeft:16, marginBottom:14, borderLeft:'3px solid var(--gold)'}}>
              <div style={{fontFamily:'Times New Roman,serif', fontSize:13, color:'var(--gold-deep)', fontWeight:700, marginBottom:4}}>{t.date}</div>
              <div style={{fontFamily:'BiauKai,標楷體,serif', fontSize:14, lineHeight:1.85, color:'var(--ink-soft)'}}>{t.note}</div>
            </div>
          ))}
        </div>
      )}

      {/* ── 財報預告 Earnings Preview（每週排程routine在財報前研究撰寫，見institutional-research-db.js schema註解）── */}
      {research.earningsPreview?.length > 0 && (
        <div className="frame-card" style={{padding:'20px 22px', marginBottom:24}}>
          <SubHead cn="財報預告" en="Earnings Preview" />
          {[...research.earningsPreview].reverse().map((p, i) => (
            <div key={i} style={{paddingLeft:16, marginBottom:14, borderLeft:'3px solid var(--ink-mute)'}}>
              <div style={{fontFamily:'Times New Roman,serif', fontSize:13, color:'var(--ink-mute)', fontWeight:700, marginBottom:6}}>{p.quarter}（預計 {p.date}）</div>
              <ul style={{fontSize:13.5, lineHeight:1.85, color:'var(--ink-soft)', paddingLeft:18, margin:0}}>
                {(p.watchPoints || []).map((w, wi) => <li key={wi}>{w}</li>)}
              </ul>
            </div>
          ))}
        </div>
      )}

      {/* ── 財報回顧記錄 ── */}
      {research.earningsLog?.length > 0 && (
        <div className="frame-card" style={{padding:'20px 22px'}}>
          <SubHead cn="財報回顧記錄" en="Earnings Review Log" />
          {[...research.earningsLog].reverse().map((e, i) => {
            const dot = e.verdict === 'beat' ? 'var(--bull)' : e.verdict === 'miss' ? 'var(--bear)' : 'var(--gold)';
            const label = e.verdict === 'beat' ? '優於預期' : e.verdict === 'miss' ? '低於預期' : '符合預期';
            return (
              <div key={i} style={{display:'flex', gap:12, marginBottom:14, alignItems:'flex-start'}}>
                <span style={{width:10, height:10, borderRadius:'50%', background:dot, marginTop:6, flexShrink:0}} />
                <div>
                  <div style={{fontSize:14, fontWeight:700, marginBottom:3}}>{e.quarter}（{e.date}）· {label}</div>
                  <div style={{fontSize:13, color:'var(--ink-mute)', lineHeight:1.75}}>{e.note}</div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── Tab5 進入點：自己 fetch financials/cashflow/現價，取代原本從 FundamentalApp 傳入的 props ───
function InstitutionalValuation({ code }) {
  const [fins, setFins] = useState([]);
  const [cashFlow, setCashFlow] = useState([]);
  const [currentPrice, setCurrentPrice] = useState(0);
  const [twEvents, setTwEvents] = useState({ dividends: [], earnings: [] });

  useEffect(function() {
    let alive = true;
    setFins([]); setCashFlow([]); setCurrentPrice(0); setTwEvents({ dividends: [], earnings: [] });
    fetch(`/api/stock?type=tw_events&code=${code}`).then(r => r.json())
      .then(d => { if (alive) setTwEvents({ dividends: d?.dividends || [], earnings: d?.earnings || [] }); })
      .catch(() => {});
    fetch(`/api/stock?type=financials&code=${code}`).then(r => r.json())
      .then(d => { if (alive) setFins(Array.isArray(d) ? d : (d.quarters || [])); })
      .catch(() => {});
    fetch(`/api/stock?type=cashflow&code=${code}`).then(r => r.json())
      .then(d => { if (alive) setCashFlow(Array.isArray(d) ? d : (d.quarters || [])); })
      .catch(() => {});
    // ⚠ fetchBWIBBU 的 TPEx(上櫃)分支目前不回傳 close 欄位，只有 TWSE(上市)股票能正確取得現價。
    // 目前 institutional-research-db.js 的12檔全是上市股，尚未踩坑；之後若研究名單加入上櫃股票，
    // 這裡會拿到 currentPrice=0 導致 DCF 卡顯示「財報資料不足」，需另接 type=realtime 備援或修 fetchBWIBBU。
    fetch(`/api/stock?type=bwibbu&code=${code}`).then(r => r.json())
      .then(d => { if (alive) setCurrentPrice(d?.close || 0); })
      .catch(() => {});
    return function() { alive = false; };
  }, [code]);

  return (
    <div style={{ padding: '28px 20px 40px', maxWidth: 880, margin: '0 auto' }}>
      <div style={{marginBottom:28}}>
        <div style={{fontFamily:'Times New Roman,serif', fontStyle:'italic', fontSize:12.5, color:'var(--gold-deep)', letterSpacing:'.14em', marginBottom:6}}>
          INSTITUTIONAL VALUATION
        </div>
        <div style={{fontFamily:'BiauKai,標楷體,serif', fontSize:24, fontWeight:700, color:'var(--ink)', letterSpacing:'.06em'}}>
          機構估值
        </div>
      </div>
      <div className="fund-desc" style={{fontSize:13, lineHeight:2, marginBottom:26}}>
        機構研究是「策展內容」，不是即時算出來的——由我實際研究每家公司的產業展望、財報、競爭態勢後寫成假設與判斷；DCF估值/同業倍數的數字則用當下最新財報活算，不是寫死的。目前只涵蓋精選約20檔大盤股，其餘個股會顯示尚未覆蓋；策展內容有時效性，需定期更新，投資決策仍須自行判斷。
      </div>
      <InstitutionalSection code={code} fins={fins} cashFlow={cashFlow} currentPrice={currentPrice} twEvents={twEvents} />
    </div>
  );
}

window.InstitutionalValuation = InstitutionalValuation;
