// =====================================================================
// LiveSpark LP — Sections (Header / Hero / Stats / Features)
// =====================================================================

// ------------------------------------------------ Logo
const Logo = ({ size = 28 }) => {
  const { C } = useLang();
  return (
    <span className="brand">
      <img
        className="brand-mark-img"
        src={C.brand.logoSrc}
        alt=""
        style={{ width: size * 1.4, height: size * 1.4 }}
      />
      <span>{C.brand.name}</span>
    </span>
  );
};

// ------------------------------------------------ Header
const Header = () => {
  const { C } = useLang();
  return (
    <header className="header">
      <div className="container header-inner">
        <a href="#top" aria-label={C.brand.name}><Logo /></a>
        <nav className="nav" aria-label="primary">
          {C.nav.map((n) => (
            <a key={n.href} href={n.href} className="nav-link">{n.label}</a>
          ))}
          <LangToggle />
          <a href={C.links.signup} className="btn btn-primary btn-sm nav-cta" aria-label={C.hero.primaryCta}>
            {C.hero.primaryCta}
            <Icon name="arrow-right" size={14} />
          </a>
        </nav>
      </div>
    </header>
  );
};

// ------------------------------------------------ Streamer silhouette (SVG)
const StreamerSilhouette = () => (
  <svg className="streamer-silhouette" viewBox="0 0 200 280" aria-hidden="true" preserveAspectRatio="xMidYEnd meet">
    <defs>
      <radialGradient id="silGrad" cx="50%" cy="30%" r="60%">
        <stop offset="0%" stopColor="rgba(255, 230, 220, 0.55)" />
        <stop offset="50%" stopColor="rgba(180, 130, 220, 0.35)" />
        <stop offset="100%" stopColor="rgba(40, 25, 70, 0.05)" />
      </radialGradient>
      <linearGradient id="hairGrad" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%"  stopColor="#3a2a5e" />
        <stop offset="100%" stopColor="#1a1238" />
      </linearGradient>
    </defs>
    {/* Hair / head silhouette */}
    <path d="M100 30 C70 30 55 55 55 85 C55 95 56 102 58 110 C50 115 45 125 48 138 C50 148 56 152 62 152 L62 165 C62 180 70 192 82 200 L82 280 L118 280 L118 200 C130 192 138 180 138 165 L138 152 C144 152 150 148 152 138 C155 125 150 115 142 110 C144 102 145 95 145 85 C145 55 130 30 100 30 Z" fill="url(#hairGrad)" />
    {/* Face highlight */}
    <ellipse cx="100" cy="105" rx="32" ry="40" fill="url(#silGrad)" />
    {/* Headphones */}
    <path d="M55 88 C55 70 70 55 100 55 C130 55 145 70 145 88" stroke="rgba(110, 99, 255, 0.7)" strokeWidth="6" fill="none" strokeLinecap="round" />
    <ellipse cx="55" cy="98" rx="8" ry="14" fill="rgba(110, 99, 255, 0.85)" />
    <ellipse cx="145" cy="98" rx="8" ry="14" fill="rgba(110, 99, 255, 0.85)" />
    {/* Shoulders */}
    <path d="M40 230 C50 200 70 195 100 195 C130 195 150 200 160 230 L160 280 L40 280 Z" fill="rgba(20, 18, 50, 0.9)" />
    {/* Mic */}
    <circle cx="65" cy="220" r="10" fill="rgba(180, 180, 200, 0.4)" />
    <rect x="62" y="225" width="6" height="40" rx="2" fill="rgba(120, 120, 140, 0.4)" />
  </svg>
);

// ------------------------------------------------ Hero stream demo (image)
const StreamDemo = () => (
  <img
    className="stream-mock-img"
    src={window.LP_CONTENT?.hero?.imageSrc || "assets/lp/hero-mock.png"}
    alt="LiveSpark のオーバーレイ機能を一覧したデモ画面"
    loading="eager"
    decoding="async"
  />
);

// ------------------------------------------------ Hero
const Hero = () => {
  const { C, lang } = useLang();
  // hero.title is a 2-line array — first line gets accent
  const [line1, line2] = C.hero.title;
  return (
    <section className="hero" id="top">
      <div className="container hero-grid">
        <div>
          <span className="eyebrow">For TikTok LIVE Creators</span>
          <h1 className="hero-title">
            {lang === "ja" ? (
              <>
                <span className="accent">TikTok LIVE</span>を、<br />
                もっと楽しく。
              </>
            ) : (
              <>
                {line1}<br />
                <span className="accent">{line2}</span>
              </>
            )}
          </h1>
          <p className="hero-sub">{C.hero.subtitle}</p>
          <div className="hero-ctas">
            <a href={C.links.signup} className="btn btn-primary btn-lg">
              {C.hero.primaryCta}<Icon name="arrow-right" size={16} />
            </a>
            <a href={C.links.custom} className="btn btn-secondary btn-lg">
              {C.hero.secondaryCta}<Icon name="arrow-right" size={16} />
            </a>
          </div>
          <div className="hero-badges">
            {C.hero.badges.map((b) => (
              <span key={b} className="hero-badge">
                <Icon name="check" size={13} />{b}
              </span>
            ))}
          </div>
        </div>

        <div className="hero-demo">
          <div className="hero-demo-inner">
            <StreamDemo />
          </div>
        </div>
      </div>
    </section>
  );
};

// ------------------------------------------------ Count-up hook
const useCountUp = (target, duration = 1400) => {
  const [val, setVal] = React.useState(target);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    let started = false;
    const start = () => {
      if (started) return;
      started = true;
      setVal(0);
      const t0 = performance.now();
      const tick = (t) => {
        const p = Math.min(1, (t - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(Math.round(target * eased));
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };

    if (typeof IntersectionObserver === "undefined") {
      start();
      return;
    }
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) start(); });
    }, { threshold: 0.2 });
    obs.observe(ref.current);
    // safety net — if observer never fires within 2s, just animate anyway
    const safety = setTimeout(start, 2000);
    return () => { obs.disconnect(); clearTimeout(safety); };
  }, [target, duration]);
  return [val, ref];
};

// ------------------------------------------------ Sparkline (animated)
const Sparkline = ({ points = [] }) => {
  const values = points.length >= 2
    ? points
    : [12, 14, 18, 17, 22, 26, 30, 35, 40, 48, 56, 63, 72, 80, 90, 100];
  const W = 320, H = 36;
  const max = Math.max(...values);
  const min = Math.min(0, ...values);
  const range = Math.max(1, max - min);
  const stepX = W / (values.length - 1);
  const coords = values.map((p, i) => [
    i * stepX,
    H - ((p - min) / range) * (H - 4) - 2,
  ]);
  // Smooth path
  const d = coords.reduce((acc, [x, y], i) => {
    if (i === 0) return `M ${x} ${y}`;
    const [px, py] = coords[i - 1];
    const cx = (px + x) / 2;
    return `${acc} Q ${cx} ${py} ${cx} ${(py + y) / 2} T ${x} ${y}`;
  }, "");
  const fill = `${d} L ${W} ${H} L 0 ${H} Z`;
  const head = coords[coords.length - 1];

  const [drawn, setDrawn] = React.useState(false);
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    if (!wrapRef.current) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setDrawn(true); });
    }, { threshold: 0.4 });
    obs.observe(wrapRef.current);
    return () => obs.disconnect();
  }, []);

  return (
    <svg ref={wrapRef} className="sparkline" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id="sparkStroke" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%"   stopColor="#4D89FF" />
          <stop offset="50%"  stopColor="#A855F7" />
          <stop offset="100%" stopColor="#22D3EE" />
        </linearGradient>
        <linearGradient id="sparkFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor="rgba(168, 85, 247, 0.35)" />
          <stop offset="100%" stopColor="rgba(168, 85, 247, 0)" />
        </linearGradient>
      </defs>
      <path className="fill" d={fill} style={{ opacity: drawn ? 1 : 0, transition: "opacity 1s ease-out 0.3s" }} />
      <path
        className="line"
        d={d}
        style={{
          strokeDasharray: 600,
          strokeDashoffset: drawn ? 0 : 600,
          transition: "stroke-dashoffset 1.6s ease-out",
        }}
      />
      <circle
        className="head"
        cx={head[0]} cy={head[1]} r="3"
        style={{ opacity: drawn ? 1 : 0, transition: "opacity 0.4s ease-out 1.5s" }}
      />
    </svg>
  );
};

// ------------------------------------------------ Stats
const StatHero = ({ item }) => {
  const [val, ref] = useCountUp(parseInt(item.value, 10) || 0);
  return (
    <div ref={ref} className="stat-card stat-hero">
      <div className="stat-hero-row">
        <span className="live-dot" />
        <span className="live-tag">LIVE</span>
        <span className="stat-hero-label">{item.label}</span>
        <span className="delta-pill" style={{ marginLeft: "auto" }}>
          <Icon name="arrow-right" size={10} />
          {item.delta || "+3 / 24h"}
        </span>
      </div>
      <div className="stat-mega num">
        {val}<span className="plus">+</span>
        <span className="unit">{item.unit}</span>
      </div>
      <Sparkline points={item.trend} />
    </div>
  );
};

const StatSat = ({ item, totalUsers = 100 }) => {
  const { lang } = useLang();
  const [val, ref] = useCountUp(parseInt(item.value, 10) || 0);
  const isPro = item.icon === "crown";
  const target = parseInt(item.value, 10) || 0;
  const sharePct = isPro ? Math.round((target / Math.max(1, totalUsers)) * 100) : 0;

  // Pro: progress toward 100 cap; Custom: show 6 thumbs (3 filled, 3 empty/upcoming)
  const pct = isPro ? Math.min(100, (val / 100) * 100) : 0;

  const thumbs = !isPro
    ? [
        { c1: "rgba(255,159,200,.55)", c2: "rgba(168,85,247,.45)", icon: "piggy" },
        { c1: "rgba(168,85,247,.55)", c2: "rgba(77,137,255,.45)", icon: "users" },
        { c1: "rgba(34,211,238,.5)",  c2: "rgba(94,234,212,.45)", icon: "truck" },
        { c1: "rgba(255,197,107,.55)", c2: "rgba(236,72,153,.4)",  icon: "toybox" },
        { c1: "rgba(110,99,255,.5)",  c2: "rgba(168,85,247,.45)", icon: "ranking" },
        { c1: "rgba(94,234,212,.5)",  c2: "rgba(34,211,238,.45)", icon: "calendar" },
      ]
    : [];

  return (
    <div ref={ref} className="stat-card stat-sat">
      <div className="stat-sat-top">
        <div className="stat-icon"><Icon name={item.icon} size={18} /></div>
        <p className="stat-sat-label">{item.label}</p>
        <span className="stat-sat-meta">
          {isPro ? "+2 / 30d" : (lang === "ja" ? "稼働中" : "Active")}
        </span>
      </div>

      <div className="stat-sat-mid">
        <p className="stat-sat-value num">{val}<span className="unit">{item.unit}</span></p>
        <p className="stat-sat-extra">
          {isPro
            ? (lang === "ja"
                ? <>全登録の<strong>{sharePct}%</strong></>
                : <><strong>{sharePct}%</strong> of total</>)
            : (lang === "ja"
                ? <>累計制作実績<br /><strong>2026 ↑</strong></>
                : <>Total shipped<br /><strong>2026 ↑</strong></>)}
        </p>
      </div>

      {isPro ? (
        <>
          <span className="stat-progress" aria-hidden="true">
            <span className="stat-progress-fill" style={{ width: `${pct}%` }} />
          </span>
          <div className="stat-progress-foot">
            <span>0</span>
            <span>{lang === "ja" ? "次マイルストーン: 50名" : "Next milestone: 50"}</span>
            <span>100</span>
          </div>
        </>
      ) : (
        <div className="stat-thumbs" aria-hidden="true">
          {thumbs.map((t, i) => (
            <div
              key={i}
              className={`stat-thumb ${i >= target ? "empty" : ""}`}
              style={{ "--c1": t.c1, "--c2": t.c2 }}
            >
              {i >= target ? <Icon name="sparkle" size={12} /> : <Icon name={t.icon} size={14} />}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const Stats = () => {
  const { C } = useLang();
  const [hero, ...rest] = C.stats.items;
  const totalUsers = parseInt(hero.value, 10) || 100;
  return (
    <section className="container section-tight">
      <div className="stats">
        <StatHero item={hero} />
        {rest.map((s) => <StatSat key={s.label} item={s} totalUsers={totalUsers} />)}
      </div>
      <p className="stats-note">{C.stats.note}</p>
    </section>
  );
};

// ------------------------------------------------ Features
const FEATURE_TONES = ["tone-bolt", "tone-spark", "tone-yen"];

const Features = () => {
  const { C, lang } = useLang();
  return (
    <section className="section" id="features">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Features</span>
          <h2 className="section-title">
            {lang === "ja" ? (
              <>LiveSparkで、<span className="holo">配信画面が変わる。</span></>
            ) : (
              <>Make your stream <span className="holo">actually fun.</span></>
            )}
          </h2>
        </div>
        <div className="feature-grid">
          {C.features.items.map((f, i) => (
            <article key={f.title} className="feature-card">
              <div className={`feature-icon ${FEATURE_TONES[i] || ""}`}>
                <Icon name={f.icon} size={26} />
              </div>
              <div>
                <h3 className="feature-title">{f.title}</h3>
                <p className="feature-body">{f.body}</p>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
};

// ------------------------------------------------ SEO intro
const SEOIntro = () => {
  const { C } = useLang();
  const block = C.seoIntro;
  return (
    <section className="section seo-intro" id="tiktok-live-overlay">
      <div className="container seo-intro-grid">
        <div className="seo-intro-copy">
          <span className="eyebrow">{block.eyebrow}</span>
          <h2 className="section-title">{block.title}</h2>
          {block.paragraphs.map((text) => (
            <p key={text}>{text}</p>
          ))}
        </div>
        <div className="seo-intro-panel">
          <div className="seo-panel-kicker">
            <span className="live-dot" />
            <span>{block.panelTitle}</span>
          </div>
          <div className="seo-point-grid">
            {block.points.map((point) => (
              <article key={point.title} className="seo-point">
                <div className="seo-point-icon">
                  <Icon name={point.icon} size={19} />
                </div>
                <div>
                  <h3>{point.title}</h3>
                  <p>{point.body}</p>
                </div>
              </article>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Logo, Header, Hero, Stats, Features, SEOIntro });
