// components.jsx — 주가 목표가 예측 플랫폼 UI 컴포넌트
// 한국어 전용 · 라이트 모드 · 미니멀

const won = (n) => n.toLocaleString("ko-KR");
const pct = (n) => (n >= 0 ? "+" : "") + n.toFixed(1) + "%";
const upside = (cur, tgt) => ((tgt - cur) / cur) * 100;

// 색 팔레트 — accent 옵션에 따라 계산
function makeColors(accent) {
  const yes = accent === "vivid" ? "#00C176" : "#11B981";
  const no = "#2A6FF0";
  return {
    bg: "#FFFFFF",
    ink: "#0E0E10",
    ink2: "#5C5C63",
    ink3: "#9A9AA2",
    hair: "#ECECEE",
    hair2: "#E0E0E3",
    chipBg: "#F5F5F6",
    yes,
    yesSoft: "rgba(17,177,124,0.12)",
    no,
    noSoft: "rgba(42,111,240,0.10)",
    up: "#E5484D",   // 등락: 상승(빨강, 한국 관습)
    down: "#2A6FF0", // 등락: 하락(파랑, 한국 관습)
    // 홈/카드용 토큰
    blue: "#2D6FF2",
    blueSoft: "#EAF1FE",
    yesText: "#15A35B",
    yesBg: "#E7F7EF",
    noText: "#E5484D",
    noBg: "#FBEBEB",
    amber: "#F0962B",
    amberSoft: "#FCEFDD",
  };
}

// 가벼운 가격 시계열 생성 (결정적) — 차트용
function priceSeries(ticker, end, n) {
  let seed = 0;
  for (const ch of ticker) seed = (seed * 31 + ch.charCodeAt(0)) % 100000;
  const rand = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
  const out = [];
  let v = end * 0.86;
  const drift = (end - v) / n;
  for (let i = 0; i < n; i++) {
    v += drift + (rand() - 0.45) * end * 0.012;
    out.push(v);
  }
  out[n - 1] = end;
  return out;
}

// ─────────────────────────────────────────── 종목 선택 탭
function StockTabs({ stocks, active, onPick, C }) {
  return (
    <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
      {stocks.map((s) => {
        const on = s.ticker === active;
        return (
          <button
            key={s.ticker}
            onClick={() => onPick(s.ticker)}
            style={{
              display: "flex", alignItems: "baseline", gap: 8,
              padding: "9px 16px", borderRadius: 999, cursor: "pointer",
              border: `1px solid ${on ? C.ink : C.hair2}`,
              background: on ? C.ink : C.bg,
              color: on ? "#fff" : C.ink,
              font: "inherit", fontWeight: 600, fontSize: 14,
              transition: "all .15s ease",
            }}
          >
            <span>{s.name}</span>
            <span style={{ fontSize: 11, fontWeight: 500, color: on ? "rgba(255,255,255,.6)" : C.ink3, fontVariantNumeric: "tabular-nums" }}>{s.ticker}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────── 종목 헤더
function StockHeader({ stock, consensus, C }) {
  const change = stock.price - stock.prevClose;
  const changePct = (change / stock.prevClose) * 100;
  const rising = change >= 0;
  const chColor = rising ? C.up : C.down;
  const consUpside = upside(stock.price, consensus);

  const Stat = ({ label, children, sub }) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <div style={{ fontSize: 12, color: C.ink3, fontWeight: 600, letterSpacing: ".02em" }}>{label}</div>
      <div style={{ fontSize: 15 }}>{children}</div>
      {sub}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 14 }}>
        <h1 style={{ margin: 0, fontSize: 34, fontWeight: 800, letterSpacing: "-.02em", color: C.ink }}>{stock.name}</h1>
        <span style={{ fontSize: 14, color: C.ink3, fontWeight: 600, fontVariantNumeric: "tabular-nums", paddingBottom: 6 }}>{stock.ticker} · {stock.sector}</span>
      </div>

      <div className="tracker-stats-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, max-content)", gap: 64, alignItems: "flex-start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <div style={{ fontSize: 12, color: C.ink3, fontWeight: 600 }}>현재가</div>
            <div style={{
              width: 6,
              height: 6,
              borderRadius: "50%",
              backgroundColor: "#00C176",
              boxShadow: "0 0 0 0 rgba(0, 193, 118, 0.7)",
              animation: "pulse 1.5s infinite"
            }} />
            <div style={{ fontSize: 10, color: "#00C176", fontWeight: 700, letterSpacing: "0.05em" }}>LIVE</div>
          </div>
          <div style={{ fontSize: 40, fontWeight: 800, letterSpacing: "-.02em", color: C.ink, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{won(stock.price)}<span style={{ fontSize: 18, fontWeight: 700, marginLeft: 3 }}>{stock.ticker === 'KOSPI' ? '포인트' : '원'}</span></div>
          <div style={{ fontSize: 15, fontWeight: 700, color: chColor, fontVariantNumeric: "tabular-nums" }}>
            {rising ? "▲" : "▼"} {won(Math.abs(change))} ({pct(changePct)})
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ fontSize: 12, color: C.ink3, fontWeight: 600 }}>증권사 평균 목표가</div>
          <div style={{ fontSize: 40, fontWeight: 800, letterSpacing: "-.02em", color: C.ink, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{won(consensus)}<span style={{ fontSize: 18, fontWeight: 700, marginLeft: 3 }}>{stock.ticker === 'KOSPI' ? '포인트' : '원'}</span></div>
          <div style={{ fontSize: 12, color: C.ink3, fontWeight: 500 }}>컨센서스 · {stock.analysts.length}개사</div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ fontSize: 12, color: C.ink3, fontWeight: 600 }}>평균 상승 여력</div>
          <div style={{ fontSize: 40, fontWeight: 800, letterSpacing: "-.02em", color: C.yes, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{pct(consUpside)}</div>
          <div style={{ fontSize: 12, color: C.ink3, fontWeight: 500 }}>현재가 대비</div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────── 게이지 바 (3종 변형)
function GaugeBar({ cur, tgt, maxTgt, variant, C }) {
  const up = upside(cur, tgt);
  // 모든 바의 스케일을 동일 maxTgt 기준으로 → 종목 내 목표가 비교 가능
  const curW = (cur / maxTgt) * 100;
  const tgtW = (tgt / maxTgt) * 100;

  if (variant === "headroom") {
    // 상승 여력(헤드룸)을 그린 그라데이션으로 강조
    return (
      <div style={{ position: "relative", height: 30, borderRadius: 7, background: C.chipBg, overflow: "hidden" }}>
        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${curW}%`, background: "#E6E6E9" }} />
        <div style={{ position: "absolute", left: `${curW}%`, top: 0, bottom: 0, width: `${tgtW - curW}%`, background: `linear-gradient(90deg, ${C.yesSoft}, ${C.yes})` }} />
        <div style={{ position: "absolute", left: `${curW}%`, top: -2, bottom: -2, width: 2, background: C.ink }} />
        <div style={{ position: "absolute", left: `calc(${curW}% + 7px)`, top: "50%", transform: "translateY(-50%)", fontSize: 10.5, fontWeight: 700, color: C.ink2 }}>현재가</div>
        <div style={{ position: "absolute", left: `${tgtW}%`, top: 0, bottom: 0, width: 2, background: C.yes }} />
      </div>
    );
  }

  if (variant === "ticks") {
    // 눈금형 — 현재가까지 채움, 목표 지점에 깃발
    const ticks = Array.from({ length: 20 }, (_, i) => i);
    return (
      <div style={{ position: "relative", height: 30 }}>
        <div style={{ position: "absolute", inset: 0, display: "flex", gap: 3, alignItems: "stretch" }}>
          {ticks.map((i) => {
            const p = (i + 0.5) * 5;
            const filled = p <= curW;
            const inHead = p > curW && p <= tgtW;
            return <div key={i} style={{ flex: 1, borderRadius: 2, background: filled ? C.ink : inHead ? C.yes : C.chipBg, opacity: inHead ? 0.35 + (p / tgtW) * 0.55 : 1 }} />;
          })}
        </div>
        <div style={{ position: "absolute", left: `calc(${tgtW}% - 1px)`, top: -3, bottom: -3, width: 2, background: C.yes }} />
      </div>
    );
  }

  // 기본 "fill" — 채움 + 헤드룸 틴트 + 목표가 끝점
  return (
    <div style={{ position: "relative", height: 30, borderRadius: 7, background: C.chipBg, overflow: "hidden" }}>
      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${tgtW}%`, background: C.yesSoft }} />
      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${curW}%`, background: C.ink }} />
      <div style={{ position: "absolute", left: `${tgtW}%`, top: 0, bottom: 0, width: 3, background: C.yes }} />
      <div style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", fontSize: 11, fontWeight: 800, color: C.yes, fontVariantNumeric: "tabular-nums" }}>{pct(up)}</div>
    </div>
  );
}

// ─────────────────────────────────────────── 로그인 모달
function LoginModal({ isOpen, onClose, C }) {
  if (!isOpen) return null;

  const doLogin = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (e && e.stopPropagation) e.stopPropagation();
    const supabase = window.supabaseClient;
    if (supabase) {
      const params = new URLSearchParams(window.location.search);
      params.delete("error");
      params.delete("error_code");
      params.delete("error_description");
      const cleanSearch = params.toString() ? "?" + params.toString() : "";
      const redirectTo = window.location.origin + window.location.pathname + cleanSearch;

      const { error } = await supabase.auth.signInWithOAuth({
        provider: 'google',
        options: { redirectTo }
      });
      if (error) console.error("Google login error:", error);
    } else {
      alert("Supabase 클라이언트가 초기화되지 않았습니다.");
    }
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 9999,
      background: "rgba(0,0,0,0.4)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20
    }} onClick={onClose}>
      <div style={{
        background: C.bg, borderRadius: 20, padding: 32, maxWidth: 360, width: "100%",
        boxShadow: "0 24px 48px rgba(0,0,0,0.12)", textAlign: "center"
      }} onClick={e => e.stopPropagation()}>
        <div style={{ width: 48, height: 48, background: C.chipBg, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" }}>
          <span style={{ fontSize: 24 }}>🗳️</span>
        </div>
        <h3 style={{ margin: "0 0 8px", fontSize: 20, fontWeight: 800, color: C.ink, letterSpacing: "-.02em" }}>투표 반영하기</h3>
        <p style={{ margin: "0 0 24px", fontSize: 14, color: C.ink3, lineHeight: 1.5 }}>
          투표를 실제 통계에 반영하려면<br/>3초 만에 구글로 로그인해주세요!
        </p>
        <button onClick={doLogin} style={{
          width: "100%", padding: "14px 0", borderRadius: 12, background: C.ink, color: "#fff",
          fontSize: 15, fontWeight: 700, border: "none", cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 8, transition: "transform 0.1s"
        }} onMouseOver={e => e.currentTarget.style.transform = "scale(1.02)"} onMouseOut={e => e.currentTarget.style.transform = "scale(1)"}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
          </svg>
          구글 로그인
        </button>
        <button onClick={onClose} style={{
          marginTop: 12, padding: "10px", background: "none", border: "none", color: C.ink3,
          fontSize: 13, fontWeight: 600, cursor: "pointer", textDecoration: "underline"
        }}>
          다음에 할게요
        </button>
      </div>
    </div>
  );
}

window.StockTabs = StockTabs;
window.StockHeader = StockHeader;
window.GaugeBar = GaugeBar;
window.LoginModal = LoginModal;
window.makeColors = makeColors;
window.priceSeries = priceSeries;
window.fmt = { won, pct, upside };
