/* global React, Button, Card, Badge, Section, SectionHeader, StatPill */
const { useState, useEffect, useRef } = React;

// ──────────────────────────────────────────
// Language Toggle (KR | EN)
// ──────────────────────────────────────────
function LangToggle() {
  const [loc, setLoc] = window.BD.useLocale();
  const opt = (val, label) => {
    const active = loc === val;
    return (
      <button
        key={val}
        onClick={() => setLoc(val)}
        aria-pressed={active}
        style={{
          height: '32px', padding: '0 14px', borderRadius: '999px',
          border: 'none', background: active ? 'var(--color-charcoal)' : 'transparent',
          color: active ? 'var(--color-ivory)' : 'rgba(26,26,26,0.6)',
          fontSize: '12px', fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          letterSpacing: '0.04em',
          transition: 'background 0.15s, color 0.15s',
        }}
        onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'var(--color-charcoal)'; }}
        onMouseLeave={e => { if (!active) e.currentTarget.style.color = 'rgba(26,26,26,0.6)'; }}
      >{label}</button>
    );
  };
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      border: '2px solid rgba(26,26,26,0.15)',
      borderRadius: '999px',
      padding: '2px',
      height: '36px',
    }}>
      {opt('ko', 'KR')}
      {opt('en', 'EN')}
    </div>
  );
}

// ──────────────────────────────────────────
// Sticky Nav
// ──────────────────────────────────────────
function StickyNav() {
  const [loc] = window.BD.useLocale();
  const c = window.BD.COPY[loc];
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    { href: '#demo', label: c.nav.demo },
    { href: '#how',  label: c.nav.how },
    { href: '#roi',  label: c.nav.roi },
    { href: '#faq',  label: c.nav.faq },
  ];
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      background: scrolled ? 'rgba(250,247,242,0.92)' : 'transparent',
      backdropFilter: scrolled ? 'saturate(180%) blur(12px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'saturate(180%) blur(12px)' : 'none',
      borderBottom: scrolled ? '1px solid rgba(26,26,26,0.06)' : '1px solid transparent',
      transition: 'all 0.25s ease',
    }}>
      <div style={{
        maxWidth: '1280px', margin: '0 auto', padding: '0 24px',
        height: '72px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="#hero" style={{ display: 'flex', alignItems: 'center', gap: '10px', textDecoration: 'none', color: 'var(--color-charcoal)' }}>
          <BadeumMark />
          <span style={{ fontWeight: 700, fontSize: '19px', letterSpacing: '-0.02em' }}>{c.brand}</span>
          <Badge variant="orange" style={{ marginLeft: '4px' }}>{c.nav.launching}</Badge>
        </a>
        <div style={{ display: 'flex', alignItems: 'center', gap: '24px' }}>
          <div style={{ display: 'flex', gap: '24px' }} className="nav-links">
            {links.map(l => (
              <a key={l.href} href={l.href} style={{
                fontSize: '14px', color: 'var(--color-charcoal)', opacity: 0.75,
                textDecoration: 'none', fontWeight: 500,
              }}>{l.label}</a>
            ))}
          </div>
          <LangToggle />
          <Button variant="primary" size="md" onClick={() => document.getElementById('cta')?.scrollIntoView({ behavior: 'smooth' })}>
            {c.nav.cta}
          </Button>
        </div>
      </div>
    </nav>
  );
}

function BadeumMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden>
      <rect x="0" y="0" width="32" height="32" rx="8" fill="#1A1A1A" />
      <path d="M9 10 C9 8.5, 10.5 7, 12 7 L20 7 C21.5 7, 23 8.5, 23 10 L23 16 L20 19 L20 22 L13 22 L9 18 Z"
        fill="#FF6A2C" />
      <circle cx="16" cy="13.5" r="1.6" fill="#1A1A1A" />
    </svg>
  );
}

// ──────────────────────────────────────────
// Hero
// ──────────────────────────────────────────
function Hero({ heroVariant, industryId }) {
  const [loc] = window.BD.useLocale();
  const c = window.BD.COPY[loc];
  const variants = loc === 'ko' ? window.BD.HERO_VARIANTS_KO : window.BD.HERO_VARIANTS_EN;
  const v = variants.find(h => h.id === heroVariant) || variants[0];
  const ind = window.BD.localIndustry(industryId, loc);

  return (
    <section id="hero" className="bg-ivory" style={{
      paddingTop: '152px', paddingBottom: '120px',
      position: 'relative', overflow: 'hidden',
    }}>
      <div aria-hidden style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse at 80% 0%, rgba(255,106,44,0.06), transparent 50%)',
      }}/>
      <div style={{ maxWidth: '1280px', margin: '0 auto', padding: '0 24px', position: 'relative' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'minmax(0, 1.15fr) minmax(0, 1fr)',
          gap: '64px', alignItems: 'center',
        }} className="hero-grid">
          <div>
            <div style={{ marginBottom: '24px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
              <Badge variant="orange">{c.hero.eyebrow}</Badge>
              <Badge variant="neutral">{c.hero.target(ind.fullLabel)}</Badge>
            </div>
            <h1 className="headline" style={{
              fontSize: 'clamp(40px, 6.4vw, 76px)', lineHeight: 1.05, fontWeight: 800,
              margin: 0, whiteSpace: 'pre-line', color: 'var(--color-charcoal)',
            }}>{v.headline}</h1>
            <p style={{
              marginTop: '28px', fontSize: 'clamp(16px, 1.4vw, 19px)', lineHeight: 1.6,
              color: 'rgba(26,26,26,0.72)', maxWidth: '560px',
            }}>{v.sub}</p>
            <div style={{ marginTop: '40px', display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
              <Button variant="primary" size="lg"
                onClick={() => document.getElementById('demo')?.scrollIntoView({ behavior: 'smooth' })}>
                {v.primary}
              </Button>
              <Button variant="secondary" size="lg"
                onClick={() => document.getElementById('cta')?.scrollIntoView({ behavior: 'smooth' })}>
                {v.secondary}
              </Button>
            </div>
            <div style={{
              marginTop: '40px', display: 'flex', alignItems: 'center', gap: '16px',
              padding: '16px 20px', background: 'rgba(255,255,255,0.6)',
              border: '1px solid rgba(26,26,26,0.06)', borderRadius: '14px', maxWidth: '480px',
            }}>
              <div className="tabular" style={{
                fontSize: '32px', fontWeight: 700, color: 'var(--color-signal)',
                letterSpacing: '-0.04em', lineHeight: 1,
              }}>{v.metric.num}</div>
              <div style={{ fontSize: '13px', color: 'rgba(26,26,26,0.7)', lineHeight: 1.4 }}>
                {v.metric.label}
              </div>
            </div>
          </div>

          <HeroVisual industry={ind} loc={loc} />
        </div>
      </div>
    </section>
  );
}

function HeroVisual({ industry, loc }) {
  const c = window.BD.COPY[loc];
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const i = setInterval(() => setTick(t => t + 1), 90);
    return () => clearInterval(i);
  }, []);
  const bars = Array.from({ length: 32 }).map((_, i) => {
    const phase = (i * 0.41 + tick * 0.18);
    return 12 + Math.abs(Math.sin(phase)) * 36 + Math.abs(Math.sin(phase * 0.5)) * 16;
  });
  const liveLabel = loc === 'ko' ? '● 통화중' : '● Live';
  const callerLabel = loc === 'ko' ? `신규 고객 · 010-****-3812` : `New caller · 010-****-3812`;
  const subLabel = loc === 'ko' ? `${industry.ctx.replace(' 커버', '')} · 받음 응대중` : `${industry.ctx.replace(' coverage','')} · Badeum answering`;

  return (
    <div style={{ position: 'relative', aspectRatio: '4/5', maxWidth: '480px', margin: '0 auto', width: '100%' }}>
      <div style={{ position: 'absolute', inset: 0, borderRadius: '28px', background: 'var(--color-trust)', transform: 'rotate(-2deg)' }}/>
      <div style={{
        position: 'absolute', inset: '12px', background: 'var(--color-ivory)',
        borderRadius: '24px', border: '1px solid rgba(26,26,26,0.08)', padding: '28px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' }}>
            <Badge variant="sage">{liveLabel}</Badge>
            <span className="tabular" style={{ fontSize: '12px', opacity: 0.5 }}>00:14</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
            <div style={{
              width: '48px', height: '48px', borderRadius: '50%', background: 'var(--color-hanji)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '22px', fontWeight: 700, color: 'var(--color-charcoal)',
            }}>{loc === 'ko' ? '김' : 'K'}</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: '15px' }}>{callerLabel}</div>
              <div style={{ fontSize: '12px', opacity: 0.55, marginTop: '2px' }}>{subLabel}</div>
            </div>
          </div>
          <div style={{
            marginTop: '20px', background: 'var(--color-hanji)', borderRadius: '14px',
            padding: '14px 16px', fontSize: '14px', lineHeight: 1.5,
          }}>
            <div style={{ fontSize: '11px', opacity: 0.5, marginBottom: '4px', fontFamily: 'IBM Plex Mono, monospace' }}>{c.demo.caller}</div>
            "{industry.sampleCaller}"
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px', height: '64px', margin: '12px 0' }}>
          {bars.map((h, i) => (
            <div key={i} style={{
              width: '4px', height: `${h}px`, background: 'var(--color-signal)',
              borderRadius: '2px', transition: 'height 90ms linear',
            }}/>
          ))}
        </div>

        <div style={{
          background: 'var(--color-trust)', color: 'var(--color-ivory)',
          borderRadius: '14px', padding: '14px 16px', fontSize: '14px', lineHeight: 1.5,
        }}>
          <div style={{ fontSize: '11px', opacity: 0.7, marginBottom: '4px', fontFamily: 'IBM Plex Mono, monospace' }}>{c.demo.ai}</div>
          "{industry.sampleAi}"
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────
// Stats-shock
// ──────────────────────────────────────────
function StatsShock() {
  const [loc] = window.BD.useLocale();
  const c = window.BD.COPY[loc];
  return (
    <Section id="stats" bg="hanji">
      <SectionHeader eyebrow={c.stats.eyebrow} title={c.stats.title} subtitle={c.stats.sub} />
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '32px', marginTop: '24px',
      }}>
        {c.stats.items.map((s, i) => (
          <div key={i} style={{
            padding: '40px 24px', background: 'rgba(255,255,255,0.5)',
            borderRadius: '20px', border: '1px solid rgba(26,26,26,0.06)',
          }}>
            <StatPill {...s} color={i === 0 || i === 1 ? 'signal' : 'trust'} />
          </div>
        ))}
      </div>
    </Section>
  );
}

// ──────────────────────────────────────────
// Vertical cards
// ──────────────────────────────────────────
function VerticalCards({ industryId, setIndustryId }) {
  const [loc] = window.BD.useLocale();
  const c = window.BD.COPY[loc];
  return (
    <Section id="verticals" bg="ivory">
      <SectionHeader eyebrow={c.verticals.eyebrow} title={c.verticals.title} subtitle={c.verticals.sub} />
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '20px',
      }}>
        {window.BD.INDUSTRIES.map(base => {
          const ind = window.BD.localIndustry(base.id, loc);
          const active = ind.id === industryId;
          return (
            <button
              key={ind.id}
              onClick={() => setIndustryId(ind.id)}
              style={{
                textAlign: 'left',
                background: active ? 'var(--color-trust)' : 'var(--color-hanji)',
                color: active ? 'var(--color-ivory)' : 'var(--color-charcoal)',
                borderRadius: '20px', padding: '28px',
                border: '1px solid ' + (active ? 'transparent' : 'rgba(26,26,26,0.06)'),
                cursor: 'pointer', transition: 'all 0.2s ease', fontFamily: 'inherit',
                display: 'flex', flexDirection: 'column', gap: '20px', minHeight: '260px',
              }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.transform = 'translateY(-2px)'; }}
              onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; }}
            >
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Badge variant={active ? 'onTrust' : 'neutral'}>{ind.ctx}</Badge>
                {active && <Badge variant="orange">{c.verticals.selected}</Badge>}
              </div>
              <div>
                <div style={{ fontSize: '13px', opacity: 0.6, marginBottom: '4px', fontFamily: 'IBM Plex Mono, monospace' }}>
                  {ind.id.toUpperCase()}
                </div>
                <h3 className="headline" style={{ fontSize: '26px', fontWeight: 700, margin: 0, lineHeight: 1.2 }}>
                  {ind.label}
                </h3>
              </div>
              <p style={{ fontSize: '14px', lineHeight: 1.55, opacity: active ? 0.85 : 0.7, margin: 0 }}>
                {ind.pain}
              </p>
              <div style={{
                marginTop: 'auto', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
                paddingTop: '16px',
                borderTop: '1px solid ' + (active ? 'rgba(255,255,255,0.15)' : 'rgba(26,26,26,0.08)'),
              }}>
                <div>
                  <div style={{ fontSize: '11px', opacity: 0.55, fontFamily: 'IBM Plex Mono, monospace' }}>{c.verticals.dailyCalls}</div>
                  <div className="tabular" style={{ fontSize: '20px', fontWeight: 600 }}>{ind.callsPerDay}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: '11px', opacity: 0.55, fontFamily: 'IBM Plex Mono, monospace' }}>{c.verticals.missRate}</div>
                  <div className="tabular" style={{ fontSize: '20px', fontWeight: 600 }}>{Math.round(ind.missRate * 100)}%</div>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </Section>
  );
}

// ──────────────────────────────────────────
// How it works
// ──────────────────────────────────────────
function HowItWorks() {
  const [loc] = window.BD.useLocale();
  const c = window.BD.COPY[loc];
  return (
    <Section id="how" bg="ivory">
      <SectionHeader eyebrow={c.how.eyebrow} title={c.how.title} />
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '24px',
      }}>
        {c.how.steps.map((s, i) => (
          <div key={i} style={{
            padding: '36px 28px 32px', background: 'var(--color-hanji)',
            borderRadius: '20px', border: '1px solid rgba(26,26,26,0.06)', position: 'relative',
          }}>
            <div className="tabular" style={{
              fontSize: '14px', fontWeight: 600, color: 'var(--color-signal)',
              letterSpacing: '0.08em', marginBottom: '20px',
            }}>{c.how.stepLabel} {s.n}</div>
            <h3 className="headline" style={{ fontSize: '24px', fontWeight: 700, margin: '0 0 12px', lineHeight: 1.25 }}>
              {s.title}
            </h3>
            <p style={{ fontSize: '15px', lineHeight: 1.6, color: 'rgba(26,26,26,0.7)', margin: 0 }}>
              {s.body}
            </p>
          </div>
        ))}
      </div>
    </Section>
  );
}

Object.assign(window, { StickyNav, Hero, StatsShock, VerticalCards, HowItWorks });
