// home-hero.jsx — 상단 내비 + 히어로 마켓 + 사이드바
const { won: hWon, pct: hPct, upside: hUpside } = window.fmt;
const SectorBadge = window.SectorBadge;

// ─────────────────────────────────────────── 상단 내비게이션
function decodeJwt(token) {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
    return JSON.parse(jsonPayload);
  } catch(e) { return null; }
}

function TopNav({ cats, activeCat, onCatChange, user, setUser, C }) {
  console.log("TopNav rendering: activeCat =", activeCat, "onCatChange =", !!onCatChange);

  // 마운트 시 한 번만 localStorage에서 사용자 복원 (Supabase가 비활성화된 경우 대비)
  React.useEffect(() => {
    if (!window.supabaseClient) {
      try {
        const saved = localStorage.getItem("pickdal_user");
        if (saved) setUser(JSON.parse(saved));
      } catch(e) {}
    }
  }, []);

  // Google Sign-In 초기화 (user 변경 시)
  React.useEffect(() => {
    const initGoogle = () => {
      if (window.google && window.google.accounts) {
        window.google.accounts.id.initialize({
          client_id: "85034864795-qpslid1u05glqkli5n7egh8npkgqu57r.apps.googleusercontent.com",
          callback: (res) => {
            const profile = decodeJwt(res.credential);
            if (profile) {
              const u = { name: profile.name, email: profile.email, picture: profile.picture };
              setUser(u);
              localStorage.setItem("pickdal_user", JSON.stringify(u));
              
              // Supabase 연동 시 ID 토큰으로 로그인 처리
              const supabase = window.supabaseClient;
              if (supabase) {
                supabase.auth.signInWithIdToken({
                  provider: 'google',
                  token: res.credential
                }).then(({ error }) => {
                  if (error) {
                    console.error("Supabase signInWithIdToken error:", error);
                    alert("Supabase 연동 로그인 실패: " + (error.message || JSON.stringify(error)));
                  }
                });
              }
            }
          }
        });
        
        const btnContainer = document.getElementById("google-login-btn");
        if (btnContainer && !user) {
          window.google.accounts.id.renderButton(btnContainer, { theme: "outline", size: "medium", type: "standard", shape: "pill" });
        }
      } else {
        setTimeout(initGoogle, 100);
      }
    };
    initGoogle();
  }, [user]);

  const handleLogout = () => {
    setUser(null);
    localStorage.removeItem("pickdal_user");
    const supabase = window.supabaseClient;
    if (supabase) {
      supabase.auth.signOut().then(() => {
        window.location.reload();
      });
    } else {
      window.location.reload();
    }
  };

  const NavLink = ({ children, active, onClick }) => (
    <button onClick={onClick} style={{
      border: "none", background: "none", cursor: "pointer", font: "inherit",
      fontSize: 14, fontWeight: active ? 700 : 600, color: active ? C.ink : C.ink2,
      padding: "4px 2px", whiteSpace: "nowrap",
    }}>{children}</button>
  );

  return (
    <header style={{ borderBottom: `1px solid ${C.hair}`, background: C.bg, position: "sticky", top: 0, zIndex: 20 }}>
      <div className="topnav-container" style={{ maxWidth: 1320, margin: "0 auto", padding: "14px 28px", display: "flex", alignItems: "center", gap: 20 }}>
        {/* 로고 */}
        <a href="/" style={{ display: "flex", alignItems: "center", gap: 9, textDecoration: "none", color: "inherit", cursor: "pointer" }}>
          <img src="Images/icons/image.png" alt="Pickdal Logo" style={{ height: 28, width: "auto", objectFit: "contain" }} />
          <span style={{ fontSize: 19, fontWeight: 800, letterSpacing: "-.02em", whiteSpace: "nowrap" }}>
            Pickdal
          </span>
        </a>
        {/* 검색 */}
        <div className="hide-on-mobile" style={{ flex: 1, maxWidth: 560, display: "flex", alignItems: "center", gap: 9, background: C.chipBg, borderRadius: 11, padding: "10px 14px" }}>
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke={C.ink3} strokeWidth="2.2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg>
          <span style={{ fontSize: 14, color: C.ink3, fontWeight: 500 }}>종목·증권사 검색</span>
          <span style={{ marginLeft: "auto", fontSize: 12, color: C.ink3, border: `1px solid ${C.hair2}`, borderRadius: 5, padding: "1px 7px", fontWeight: 600 }}>/</span>
        </div>
        
        <div className="topnav-right" style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 18 }}>
          <span className="hide-on-mobile"><NavLink>이용 방법</NavLink></span>
          {user ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <img src={user.picture} alt="Profile" style={{ width: 32, height: 32, borderRadius: "50%", border: `1px solid ${C.hair}` }} />
              <span style={{ fontSize: 14, fontWeight: 700, color: C.ink }}>{user.name}</span>
              <button onClick={handleLogout} style={{ border: `1px solid ${C.hair2}`, background: "transparent", cursor: "pointer", font: "inherit", fontSize: 13, fontWeight: 600, color: C.ink2, padding: "6px 12px", borderRadius: 8 }}>로그아웃</button>
            </div>
          ) : (
            <div id="google-login-btn"></div>
          )}
        </div>
      </div>
      {/* 카테고리 */}
      <div className="category-tabs-container" style={{ maxWidth: 1320, margin: "0 auto", padding: "0 28px 12px", display: "flex", alignItems: "center", gap: 18, overflowX: "auto" }}>
        <button onClick={() => { console.log("clicked 인기"); onCatChange("전체"); }} style={{
          border: "none", background: "none", cursor: "pointer", font: "inherit",
          fontSize: 14, fontWeight: activeCat === "전체" ? 700 : 600, color: activeCat === "전체" ? C.ink : C.ink2,
          padding: "4px 2px", whiteSpace: "nowrap",
        }}>인기</button>
        <button onClick={() => onCatChange("전체")} style={{
          border: "none", background: "none", cursor: "pointer", font: "inherit",
          fontSize: 14, fontWeight: 600, color: C.ink2,
          padding: "4px 2px", whiteSpace: "nowrap",
        }}>최신</button>
        <div style={{ width: 1, height: 16, background: C.hair2 }} />
        {cats.slice(1).map((c) => (
          <button key={c} onClick={() => { console.log("clicked", c); onCatChange(c); }} style={{
            border: "none", background: "none", cursor: "pointer", font: "inherit",
            fontSize: 14, fontWeight: activeCat === c ? 700 : 600, color: activeCat === c ? C.ink : C.ink2,
            padding: "4px 2px", whiteSpace: "nowrap",
          }}>{c}</button>
        ))}
      </div>
    </header>
  );
}

// ─────────────────────────────────────────── 가격 차트 (SVG)
function PriceChart({ series, target, C }) {
  const W = 600, H = 300, padR = 72, padT = 18, padB = 30;
  const lo = Math.min(...series), hi = Math.max(target, ...series);
  const range = (hi - lo) || 1;
  const x = (i) => 4 + (i / (series.length - 1)) * (W - 4 - padR);
  const y = (v) => padT + (1 - (v - lo) / range) * (H - padT - padB);
  const pts = series.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
  const ty = y(target);
  const lastX = x(series.length - 1), lastY = y(series[series.length - 1]);
  const areaPts = `4,${H - padB} ${pts} ${lastX.toFixed(1)},${H - padB}`;

  return (
    <div style={{ position: "relative", width: "100%" }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", display: "block" }}>
        <defs>
          <linearGradient id="chartFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={C.amber} stopOpacity="0.16" />
            <stop offset="100%" stopColor={C.amber} stopOpacity="0" />
          </linearGradient>
        </defs>
        {/* 목표가 라인 */}
        <line x1="4" y1={ty} x2={W - padR} y2={ty} stroke={C.ink3} strokeWidth="1.2" strokeDasharray="4 4" />
        {/* 영역 */}
        <polygon points={areaPts} fill="url(#chartFill)" />
        {/* 가격 라인 */}
        <polyline points={pts} fill="none" stroke={C.amber} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" />
        {/* 현재 점 */}
        <circle cx={lastX} cy={lastY} r="4.5" fill={C.amber} stroke="#fff" strokeWidth="2" />
        {/* 목표 pill */}
        <g>
          <rect x={W - padR + 2} y={ty - 11} width={padR - 6} height="22" rx="11" fill={C.ink} />
          <text x={W - padR / 2} y={ty + 4} textAnchor="middle" fill="#fff" fontSize="11" fontWeight="700">목표가</text>
        </g>
      </svg>
    </div>
  );
}

// ─────────────────────────────────────────── 히어로 마켓

function HeroMarket({ stock, votes, voteKey, onVote, onOpen, C }) {
  const [index, setIndex] = React.useState(0);

  React.useEffect(() => {
    setIndex(0);
    if (!stock.analysts || stock.analysts.length <= 1) return;
    const interval = setInterval(() => {
      setIndex((prev) => (prev + 1) % stock.analysts.length);
    }, 4000); // 4 seconds rotation
    return () => clearInterval(interval);
  }, [stock.ticker]);

  const activeIndex = (stock.analysts && index < stock.analysts.length) ? index : 0;
  const top = (stock.analysts && stock.analysts[activeIndex]) || { firm: "정보 없음", target: stock.price, date: "", yes: 1, no: 1 };

  const k = top.firm !== "정보 없음" && voteKey ? voteKey(stock.ticker, top.firm) : null;
  const v = k && votes ? votes[k] : { yes: top.yes, no: top.no, my: null };
  const tot = v ? v.yes + v.no : top.yes + top.no;
  const yp = tot ? Math.round((v.yes / tot) * 100) : 50;
  const np = 100 - yp;
  const my = v ? v.my : null;
  const up = hUpside(stock.price, top.target);
  const series = window.priceSeries(stock.ticker, stock.price, 48);

  const Stat = ({ label, val, unit, color }) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <div style={{ fontSize: 11.5, color: C.ink3, fontWeight: 600, whiteSpace: "nowrap" }}>{label}</div>
      <div style={{ fontSize: 21, fontWeight: 800, color: color || C.ink, letterSpacing: "-.01em", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>{val}<span style={{ fontSize: 12, fontWeight: 700, marginLeft: 2 }}>{unit}</span></div>
    </div>
  );

  const BigBtn = ({ side, label, p, primary }) => {
    const isSelected = my === side;
    return (
      <button onClick={(e) => { e.stopPropagation(); if (onVote) onVote(stock.ticker, top.firm, side); }} style={{
        flex: 1, cursor: "pointer", font: "inherit", borderRadius: 12, padding: "14px 16px",
        border: `1.5px solid ${isSelected ? (primary ? C.yesText : C.noText) : C.hair2}`,
        background: isSelected ? (primary ? C.yesText : C.noText) : (primary ? C.yesBg : C.chipBg),
        display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 2,
        transition: "all .12s ease",
      }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: isSelected ? "#fff" : (primary ? C.yesText : C.ink2), whiteSpace: "nowrap" }}>{label}</span>
        <span style={{ fontSize: 24, fontWeight: 800, color: isSelected ? "#fff" : (primary ? C.yesText : C.ink), fontVariantNumeric: "tabular-nums" }}>{p}%</span>
      </button>
    );
  };

  return (
    <div className="hero-market-container" style={{ border: `1px solid ${C.hair2}`, borderRadius: 18, padding: 24, background: C.bg }}>
      {/* 상단 */}
      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, flexWrap: "wrap" }}>
        <div className="hero-market-title-block" style={{ display: "flex", gap: 13, alignItems: "center", flex: 1, minWidth: 280 }}>
          <SectorBadge name={stock.name} sector={stock.sector} size={48} C={C} />
          <div>
            <div style={{ fontSize: 21, fontWeight: 800, letterSpacing: "-.02em", lineHeight: 1.25 }}>{stock.name}, {hWon(top.target)}{stock.ticker === 'KOSPI' ? '포인트' : '원'} 달성할까?</div>
            <div style={{ fontSize: 12.5, color: C.ink3, fontWeight: 500, marginTop: 3 }}>{top.firm} 목표가 · {top.date} 리포트</div>
          </div>
        </div>
        <div className="hero-market-stats" style={{ display: "flex", gap: 32 }}>
          <Stat label="현재가" val={hWon(stock.price)} unit={stock.ticker === 'KOSPI' ? '포인트' : '원'} />
          <Stat label="목표가" val={hWon(top.target)} unit={stock.ticker === 'KOSPI' ? '포인트' : '원'} />
          <Stat label="상승 여력" val={hPct(up)} color={C.yesText} />
        </div>
      </div>

      {/* 본문 2열 */}
      <div className="hero-market-inner-grid" style={{ display: "grid", gridTemplateColumns: "minmax(260px, 0.85fr) 1.3fr", gap: 28, marginTop: 22 }}>
        {/* 좌: 버튼 + 코멘트 */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", gap: 10 }}>
            <BigBtn side="yes" label="달성 YES" p={yp} primary />
            <BigBtn side="no" label="미달 NO" p={np} />
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingTop: 4 }}>
            <div style={{ fontSize: 11.5, color: C.ink3, fontWeight: 700, letterSpacing: ".02em" }}>리서치 핵심 근거</div>
            {stock.analysts && stock.analysts.slice(0, 3).map((a, i) => (
              <div key={i} style={{ display: "flex", gap: 9, alignItems: "flex-start" }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: C.yesSoft, color: C.yesText,
                  flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 11, fontWeight: 800
                }}>{a.firm[0]}</div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 700, color: C.ink }}>{a.firm}</span>
                    <span style={{ fontSize: 11, color: C.ink3, fontWeight: 500 }}>{a.date}</span>
                  </div>
                  <div style={{ fontSize: 12, color: C.ink2, lineHeight: 1.45, marginTop: 2, wordBreak: "keep-all" }}>
                    {a.reason || "상세 근거는 개별 리포트 참조"}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
        {/* 우: 차트 */}
        <div style={{ display: "flex", flexDirection: "column" }}>
          <PriceChart series={series} target={top.target} C={C} />
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8 }}>
            {(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" }}>투표 {hWon(tot)}명 참여</span>
            )}
            <span style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: C.ink3, fontWeight: 600, whiteSpace: "nowrap" }}>
              <span style={{
                width: 6,
                height: 6,
                borderRadius: "50%",
                backgroundColor: C.noText,
                boxShadow: `0 0 0 0 ${C.noText}b3`,
                animation: "pulse-red 1.5s infinite",
                display: "inline-block"
              }} />실시간
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────── 사이드바
function Sidebar({ stocks, onOpen, C }) {
  // 주목 목표가 — 상승여력 큰 순
  const notable = stocks.map((s) => {
    const top = [...s.analysts].sort((a, b) => b.target - a.target)[0];
    const tot = s.analysts.reduce((x, a) => x + a.yes + a.no, 0);
    const yes = s.analysts.reduce((x, a) => x + a.yes, 0);
    return { s, top, up: hUpside(s.price, top.target), yp: Math.round((yes / tot) * 100), vol: tot };
  });
  const byUp = [...notable].sort((a, b) => b.up - a.up).slice(0, 3);
  const byVol = [...notable].sort((a, b) => b.vol - a.vol);

  const Card = ({ title, children }) => (
    <div style={{ border: `1px solid ${C.hair2}`, borderRadius: 16, padding: "18px 18px 8px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
        <span style={{ fontSize: 15, fontWeight: 800, letterSpacing: "-.01em", whiteSpace: "nowrap" }}>{title}</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.ink3} strokeWidth="2.4" strokeLinecap="round"><path d="M9 18l6-6-6-6"/></svg>
      </div>
      {children}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Card title="주목 목표가">
        {byUp.map((n, i) => (
          <div key={n.s.ticker} onClick={() => onOpen(n.s.ticker)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderTop: i ? `1px solid ${C.hair}` : "none", cursor: "pointer" }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: C.ink3, width: 12 }}>{i + 1}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: C.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{n.s.name} {hWon(n.top.target)}{n.s.ticker === 'KOSPI' ? '포인트' : '원'}</div>
              <div style={{ fontSize: 11.5, color: C.ink3, fontWeight: 500 }}>{n.top.firm}</div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 14, fontWeight: 800, color: C.yesText, fontVariantNumeric: "tabular-nums" }}>{n.yp}%</div>
              <div style={{ fontSize: 11, fontWeight: 700, color: C.yesText, fontVariantNumeric: "tabular-nums" }}>{hPct(n.up)}</div>
            </div>
          </div>
        ))}
      </Card>

      <Card title="인기 종목">
        {byVol.map((n, i) => (
          <div key={n.s.ticker} onClick={() => onOpen(n.s.ticker)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderTop: i ? `1px solid ${C.hair}` : "none", cursor: "pointer" }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: C.ink3, width: 12 }}>{i + 1}</span>
            <span style={{ flex: 1, fontSize: 13.5, fontWeight: 700, color: C.ink }}>{n.s.name}</span>
            {(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') && (
              <span style={{ fontSize: 12.5, color: C.ink2, fontWeight: 600, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>투표 {hWon(n.vol)}</span>
            )}
            <span style={{ fontSize: 12 }}>🔥</span>
          </div>
        ))}
      </Card>

      <button style={{ border: `1px solid ${C.hair2}`, background: C.bg, cursor: "pointer", font: "inherit", borderRadius: 14, padding: "15px", fontWeight: 700, fontSize: 14, color: C.ink }}>전체 탐색</button>
    </div>
  );
}

window.TopNav = TopNav;
window.HeroMarket = HeroMarket;
window.Sidebar = Sidebar;
window.PriceChart = PriceChart;
