const { useState: useStateHero, useEffect: useEffectHero, useRef: useRefHero } = React;

// Sample call transcript that plays on loop
const TRANSCRIPT = [
  { speaker: 'caller', text: "Hi, I want to book a table for four tonight at 8.", delay: 0 },
  { speaker: 'agent', text: "Of course — let me check 8 PM for four guests. One moment.", delay: 2200 },
  { speaker: 'agent', text: "We have a window table available. Any dietary preferences?", delay: 4400 },
  { speaker: 'caller', text: "One vegetarian, and we'll need a high chair.", delay: 6600 },
  { speaker: 'agent', text: "Noted. May I have the name and a contact number?", delay: 8800 },
  { speaker: 'caller', text: "Hassan Ali — 0312 4567890.", delay: 11000 },
  { speaker: 'agent', text: "Perfect, Hassan. Booked: 8 PM, table for 4, vegetarian + high chair. Confirmation sent via SMS.", delay: 13200 },
];

function Hero({ tweaks }) {
  const [step, setStep] = useStateHero(0);
  const [elapsed, setElapsed] = useStateHero(0);

  // Loop transcript every ~17s
  useEffectHero(() => {
    const start = Date.now();
    const tick = setInterval(() => {
      const t = (Date.now() - start) % 17000;
      setElapsed(t);
      let s = 0;
      for (let i = 0; i < TRANSCRIPT.length; i++) {
        if (t >= TRANSCRIPT[i].delay) s = i;
      }
      setStep(s);
    }, 100);
    return () => clearInterval(tick);
  }, []);

  const headlineStyle = tweaks?.headlineStyle || 'serif-mix';

  return (
    <section id="top" style={{
      position: 'relative',
      padding: '72px 48px 120px',
      maxWidth: 1440, margin: '0 auto',
      overflow: 'hidden',
    }}>
      {tweaks?.showGrid && (
        <div className="grid-bg" style={{
          position: 'absolute', inset: 0,
          maskImage: 'radial-gradient(ellipse at 50% 30%, black 30%, transparent 75%)',
          WebkitMaskImage: 'radial-gradient(ellipse at 50% 30%, black 30%, transparent 75%)',
          opacity: 0.6,
          pointerEvents: 'none',
        }}/>
      )}

      <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 64, alignItems: 'center' }}>
        {/* LEFT — copy */}
        <div className="fade-up">
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '6px 12px',
            background: 'var(--bg)',
            border: '1px solid var(--line)',
            borderRadius: 999,
            fontSize: 12, color: 'var(--ink-2)',
            marginBottom: 32,
          }}>
            <span className="live-dot" style={{
              width: 7, height: 7, borderRadius: 999,
              background: 'var(--accent)',
              boxShadow: '0 0 0 3px var(--accent-soft)',
            }}/>
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.04em' }}>
              LIVE · 2,418 CALLS HANDLED TODAY
            </span>
          </div>

          <h1 style={{
            fontSize: 'clamp(48px, 6.4vw, 92px)',
            lineHeight: 1.04,
            letterSpacing: '-0.03em',
            marginBottom: 36,
            paddingBottom: 4,
            fontWeight: headlineStyle === 'all-sans' ? 600 : 400,
          }}>
            {headlineStyle === 'all-sans' ? (
              <>Never miss a call.<br/>Never hire a receptionist.</>
            ) : headlineStyle === 'all-serif' ? (
              <span className="serif">Never miss a call.<br/>Never hire a receptionist.</span>
            ) : (
              <>
                <span className="serif">Never miss</span>{' '}
                <span style={{ fontWeight: 500 }}>a call.</span>
                <br/>
                <span style={{ fontWeight: 500 }}>Never hire</span>{' '}
                <span className="serif italic">a receptionist.</span>
              </>
            )}
          </h1>

          <p style={{
            fontSize: 19, lineHeight: 1.5,
            color: 'var(--ink-2)',
            maxWidth: 520,
            marginBottom: 40,
          }}>
            Our AI voice agent answers every inbound call, handles the conversation in a natural human voice, and logs everything to your dashboard — 24/7, in Urdu and English.
          </p>

          <div style={{ display: 'flex', gap: 12, marginBottom: 56 }}>
            <a href="#cta" style={{
              background: 'var(--ink)', color: 'var(--bg)',
              padding: '16px 28px', borderRadius: 999,
              fontSize: 15, fontWeight: 500,
              display: 'inline-flex', alignItems: 'center', gap: 10,
            }}>
              Book Now
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 7h8m-3-3 3 3-3 3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </a>
            <a href="#how" style={{
              background: 'transparent', color: 'var(--ink)',
              padding: '16px 24px', borderRadius: 999,
              fontSize: 15, fontWeight: 500,
              border: '1px solid var(--line)',
              display: 'inline-flex', alignItems: 'center', gap: 10,
            }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 20, height: 20, borderRadius: 999,
                background: 'var(--accent-soft)', color: 'var(--accent-ink)',
              }}>
                <svg width="8" height="8" viewBox="0 0 8 8"><path d="M1 1 L7 4 L1 7 Z" fill="currentColor"/></svg>
              </span>
              Hear it in action
            </a>
          </div>

          {/* Stat badges */}
          <div style={{ display: 'flex', gap: 0, borderTop: '1px solid var(--line)', paddingTop: 24 }}>
            <Stat number="24/7" label="Always available" />
            <Stat number="0" label="Missed calls" accent />
            <Stat number="< 0.4s" label="Pickup latency" />
          </div>
        </div>

        {/* RIGHT — live call simulation */}
        <CallSimulator step={step} elapsed={elapsed} />
      </div>
    </section>
  );
}

function Stat({ number, label, accent }) {
  return (
    <div style={{
      flex: 1,
      paddingRight: 24,
      borderRight: '1px solid var(--line)',
    }}>
      <div className="serif" style={{
        fontSize: 44, lineHeight: 1,
        color: accent ? 'var(--accent-ink)' : 'var(--ink)',
        letterSpacing: '-0.02em',
        marginBottom: 8,
      }}>{number}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
        {label}
      </div>
    </div>
  );
}

function CallSimulator({ step, elapsed }) {
  const seconds = Math.floor(elapsed / 1000);
  const mm = String(Math.floor(seconds / 60)).padStart(2, '0');
  const ss = String(seconds % 60).padStart(2, '0');

  return (
    <div style={{
      position: 'relative',
      background: 'white',
      border: '1px solid var(--line)',
      borderRadius: 24,
      padding: 24,
      boxShadow: '0 30px 60px -30px oklch(0.5 0.02 60 / 0.18), 0 8px 20px -10px oklch(0.5 0.02 60 / 0.08)',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        paddingBottom: 18,
        borderBottom: '1px solid var(--line-2)',
        marginBottom: 18,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 12,
            background: 'var(--accent-soft)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
              <path d="M3 4.5C3 3.67 3.67 3 4.5 3h2L8 6 6 7c.83 2.5 2.5 4.17 5 5l1-2 3 1.5v2c0 .83-.67 1.5-1.5 1.5C7.6 15 3 10.4 3 4.5Z" stroke="var(--accent-ink)" strokeWidth="1.4" strokeLinejoin="round"/>
            </svg>
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Incoming call</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
              +92 312 456 7890
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="live-dot" style={{
            width: 8, height: 8, borderRadius: 999,
            background: 'var(--accent)',
          }}/>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>{mm}:{ss}</span>
        </div>
      </div>

      {/* Waveform */}
      <Waveform />

      {/* Status row */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        margin: '18px 0',
        fontSize: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            width: 24, height: 24, borderRadius: 999,
            background: 'var(--accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
              <path d="M5 1v5m-2-2 2 2 2-2M2 8h6" stroke="white" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div>
            <div style={{ fontWeight: 600, color: 'var(--ink)' }}>AxisAgent</div>
            <div style={{ fontSize: 10, color: 'var(--ink-3)' }} className="mono">
              MODEL · CALLAXIS-V3 · UR/EN
            </div>
          </div>
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
          Intent: reservation
        </div>
      </div>

      {/* Transcript */}
      <div style={{
        background: 'var(--bg-2)',
        borderRadius: 14,
        padding: 16,
        height: 220,
        overflow: 'hidden',
        position: 'relative',
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      }}>
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: 30,
          background: 'linear-gradient(to bottom, var(--bg-2), transparent)',
          zIndex: 1,
        }}/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {TRANSCRIPT.slice(Math.max(0, step - 2), step + 1).map((line, i, arr) => (
            <TranscriptLine
              key={`${step}-${i}`}
              line={line}
              fresh={i === arr.length - 1}
            />
          ))}
        </div>
      </div>

      {/* Action bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginTop: 16, paddingTop: 16,
        borderTop: '1px solid var(--line-2)',
      }}>
        <div style={{ display: 'flex', gap: 18, fontSize: 11 }} className="mono">
          <Tag dot="var(--accent)">LOGGED</Tag>
          <Tag dot="var(--accent)">TRANSCRIBED</Tag>
          <Tag dot="oklch(0.85 0.05 80)">SMS QUEUED</Tag>
        </div>
        <button style={{
          fontSize: 11, color: 'var(--ink-3)',
          padding: '6px 12px', border: '1px solid var(--line)',
          borderRadius: 999,
        }} className="mono">
          → Transfer to human
        </button>
      </div>
    </div>
  );
}

function Waveform() {
  // 56 bars with varied heights
  const bars = Array.from({ length: 56 }, (_, i) => {
    const seed = (Math.sin(i * 1.7) + 1) / 2;
    return 0.25 + seed * 0.7;
  });
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 3,
      height: 60,
    }}>
      {bars.map((h, i) => (
        <div
          key={i}
          className="wave-bar"
          style={{
            flex: 1,
            background: i % 7 === 0 ? 'var(--accent)' : 'var(--ink)',
            opacity: i % 7 === 0 ? 1 : 0.65,
            height: `${h * 100}%`,
            borderRadius: 2,
            animationDelay: `${(i % 12) * 0.07}s`,
            animationDuration: `${0.8 + (i % 5) * 0.15}s`,
          }}
        />
      ))}
    </div>
  );
}

function TranscriptLine({ line, fresh }) {
  const isAgent = line.speaker === 'agent';
  return (
    <div style={{
      display: 'flex',
      flexDirection: isAgent ? 'row' : 'row-reverse',
      gap: 8,
      opacity: fresh ? 1 : 0.55,
      transition: 'opacity 0.4s',
      animation: fresh ? 'fadeUp 0.5s ease-out' : 'none',
    }}>
      <div style={{
        flexShrink: 0,
        width: 22, height: 22, borderRadius: 999,
        background: isAgent ? 'var(--accent)' : 'var(--ink)',
        color: 'white',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 9, fontWeight: 600,
      }} className="mono">
        {isAgent ? 'AI' : 'C'}
      </div>
      <div style={{
        background: isAgent ? 'white' : 'var(--ink)',
        color: isAgent ? 'var(--ink)' : 'var(--bg)',
        padding: '8px 12px',
        borderRadius: 12,
        fontSize: 13, lineHeight: 1.4,
        maxWidth: '78%',
        border: isAgent ? '1px solid var(--line-2)' : 'none',
      }}>
        {line.text}
      </div>
    </div>
  );
}

function Tag({ dot, children }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      color: 'var(--ink-3)',
      letterSpacing: '0.04em',
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 999, background: dot }}/>
      {children}
    </span>
  );
}

window.Hero = Hero;
window.Marquee = function Marquee() {
  const items = [
    'KARACHI BIRYANI HOUSE', 'DR. KHAN CLINIC', 'ZARA REAL ESTATE',
    'BOLT MOTORS', 'GREEN LEAF PHARMACY', 'NORTH STAR LOGISTICS',
    'AALI DENTAL', 'SHAHEEN AUTO', 'CRESCENT SALON',
    'METRO MART', 'EVERFRESH GROCERS', 'HORIZON PROPERTIES',
  ];
  return (
    <div style={{
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
      padding: '20px 0',
      overflow: 'hidden',
      background: 'var(--bg-2)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 48px 12px', maxWidth: 1440, margin: '0 auto' }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>
          ANSWERING CALLS FOR
        </span>
      </div>
      <div style={{ display: 'flex', overflow: 'hidden', maskImage: 'linear-gradient(to right, transparent, black 8%, black 92%, transparent)', WebkitMaskImage: 'linear-gradient(to right, transparent, black 8%, black 92%, transparent)' }}>
        <div className="marquee-track" style={{ display: 'flex', gap: 56, paddingRight: 56, flexShrink: 0 }}>
          {[...items, ...items].map((item, i) => (
            <span key={i} className="mono" style={{
              fontSize: 13,
              color: 'var(--ink-2)',
              letterSpacing: '0.08em',
              whiteSpace: 'nowrap',
              display: 'inline-flex', alignItems: 'center', gap: 14,
            }}>
              {item}
              <span style={{ width: 4, height: 4, borderRadius: 999, background: 'var(--ink-3)', opacity: 0.4 }}/>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
};
