// home-cards.jsx — 마켓 카드 그리드 (홈)
const HC = { fmt: window.fmt };
const { won: hcWon, pct: hcPct, upside: hcUpside } = window.fmt;

// 섹터 배지 색
const SECTOR_STYLE = {
  "반도체":   { bg: "#EAF1FE", fg: "#2D6FF2" },
  "인터넷":   { bg: "#E7F7EF", fg: "#15A35B" },
  "자동차":   { bg: "#FCEFDD", fg: "#C9781B" },
  "2차전지":  { bg: "#F1ECFE", fg: "#7A52D8" },
  "투자/지주": { bg: "#FCEFDD", fg: "#F0962B" },
  "IT부품":   { bg: "#E7F7EF", fg: "#00C176" },
  "조선":     { bg: "#EAF1FE", fg: "#2A6FF0" },
  "금융":     { bg: "#FBEBEB", fg: "#E5484D" },
  "에너지":   { bg: "#F1ECFE", fg: "#7A52D8" },
  "건설/상사": { bg: "#F5F5F6", fg: "#5C5C63" },
};

function SectorBadge({ name, sector, size = 40, C }) {
  const st = SECTOR_STYLE[sector] || { bg: C.chipBg, fg: C.ink2 };
  return (
    <div style={{
      width: size, height: size, borderRadius: 10, flexShrink: 0,
      background: st.bg, color: st.fg,
      display: "flex", alignItems: "center", justifyContent: "center",
      fontSize: size * 0.42, fontWeight: 800, letterSpacing: "-.02em",
    }}>{name[0]}</div>
  );
}

// 예 / 아니오 미니 버튼 (카드 행)
function YesNoMini({ my, onVote, C }) {
  const base = {
    border: "none", cursor: "pointer", font: "inherit", fontWeight: 700,
    fontSize: 12.5, padding: "6px 0", width: 46, borderRadius: 7,
    transition: "all .12s ease",
  };
  return (
    <div style={{ display: "flex", gap: 6 }}>
      <button onClick={(e) => { e.stopPropagation(); onVote("yes"); }}
        style={{ ...base, background: my === "yes" ? C.yesText : C.yesBg, color: my === "yes" ? "#fff" : C.yesText }}>예</button>
      <button onClick={(e) => { e.stopPropagation(); onVote("no"); }}
        style={{ ...base, background: my === "no" ? C.noText : C.noBg, color: my === "no" ? "#fff" : C.noText }}>아니오</button>
    </div>
  );
}

// 종목 카드
function StockCard({ stock, votes, voteKey, onVote, onOpen, isNew, C }) {
  const consensus = Math.round(stock.analysts.reduce((s, a) => s + a.target, 0) / stock.analysts.length);
  const consUp = hcUpside(stock.price, consensus);
  // 목표가 높은 순 상위 2개
  const top = [...stock.analysts].sort((a, b) => b.target - a.target).slice(0, 2);

  let totalVotes = 0;
  stock.analysts.forEach((a) => { const v = votes[voteKey(stock.ticker, a.firm)]; totalVotes += v.yes + v.no; });

  return (
    <div onClick={onOpen}
      style={{
        border: `1px solid ${C.hair2}`, borderRadius: 14, background: C.bg,
        padding: 18, cursor: "pointer", display: "flex", flexDirection: "column",
        gap: 14, transition: "box-shadow .15s ease, border-color .15s ease",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = "0 6px 22px rgba(15,15,20,.07)"; e.currentTarget.style.borderColor = C.hair; }}
      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = "none"; e.currentTarget.style.borderColor = C.hair2; }}
    >
      {/* 헤더 */}
      <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
        <SectorBadge name={stock.name} sector={stock.sector} C={C} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15.5, fontWeight: 700, color: C.ink, lineHeight: 1.3 }}>{stock.name} 목표가, 달성할까?</div>
          <div style={{ fontSize: 12, color: C.ink3, fontWeight: 500, marginTop: 3, fontVariantNumeric: "tabular-nums" }}>
            현재가 {hcWon(stock.price)}{stock.ticker === 'KOSPI' ? '포인트' : '원'} · 컨센서스 {hcPct(consUp)}
          </div>
        </div>
      </div>

      {/* 타깃 행 */}
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {top.map((a) => {
          const k = voteKey(stock.ticker, a.firm);
          const v = votes[k];
          const tot = v.yes + v.no;
          const yp = tot ? Math.round((v.yes / tot) * 100) : 50;
          return (
            <div key={a.firm} style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: C.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.firm}</div>
                <div style={{ fontSize: 11.5, color: C.ink3, fontWeight: 500, fontVariantNumeric: "tabular-nums" }}>{hcWon(a.target)}{stock.ticker === 'KOSPI' ? '포인트' : '원'} · {hcPct(hcUpside(stock.price, a.target))}</div>
              </div>
              <div style={{ fontSize: 18, fontWeight: 800, color: yp >= 50 ? C.yesText : C.ink, fontVariantNumeric: "tabular-nums", width: 46, textAlign: "right" }}>{yp}%</div>
              <YesNoMini my={v.my} onVote={(side) => onVote(stock.ticker, a.firm, side)} C={C} />
            </div>
          );
        })}
      </div>

      {/* 푸터 */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", borderTop: `1px solid ${C.hair}`, paddingTop: 12, marginTop: 2 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') && (
            <span style={{ fontSize: 12, color: C.ink3, fontWeight: 600, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>투표 {hcWon(totalVotes)}</span>
          )}
          {isNew && <span style={{ fontSize: 11, fontWeight: 700, color: C.amber, whiteSpace: "nowrap" }}>✦ 신규</span>}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12, color: C.blue, fontWeight: 700, whiteSpace: "nowrap" }}>
          전체 보기
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
        </div>
      </div>
    </div>
  );
}

// 카테고리 필터 탭
function CategoryTabs({ cats, active, onPick, C }) {
  return (
    <div style={{ display: "flex", gap: 6, overflowX: "auto", paddingBottom: 4 }}>
      {cats.map((c) => {
        const on = c === active;
        return (
          <button key={c} onClick={() => onPick(c)}
            style={{
              border: "none", cursor: "pointer", font: "inherit", whiteSpace: "nowrap",
              padding: "8px 15px", borderRadius: 9, fontWeight: 700, fontSize: 13.5,
              background: on ? C.blueSoft : "transparent",
              color: on ? C.blue : C.ink2, transition: "all .12s ease",
            }}>{c}</button>
        );
      })}
    </div>
  );
}

window.StockCard = StockCard;
window.CategoryTabs = CategoryTabs;
window.SectorBadge = SectorBadge;
