/* global React */
/* Bature Digital — Hero Story
   An animated narrative replacing the static hero panel.
   Tells the story of compounding progress across 5 marketing channels.
*/

const { useEffect, useState, useRef } = React;

const STAGES = [
  {
    key: 'seo',
    label: 'SEO',
    eyebrow: 'Month 1 — SEO',
    headline: 'Climbing search rankings',
    sub: 'From page 4 to page 1',
    metric: { from: 20, to: 407, suffix: ' clicks/mo' },
    color: '#F1C518',
  },
  {
    key: 'ads',
    label: 'Paid Ads',
    eyebrow: 'Month 3 — Paid Ads',
    headline: 'ROAS compounding',
    sub: 'Spend tightened, returns up',
    metric: { from: 1.2, to: 4.8, suffix: '× ROAS', decimals: 1 },
    color: '#A77FD0',
  },
  {
    key: 'social',
    label: 'Social',
    eyebrow: 'Month 5 — Social',
    headline: 'Audience growing',
    sub: 'Real reach, not vanity',
    metric: { from: 1.2, to: 14.6, suffix: 'K followers', decimals: 1 },
    color: '#F5D24A',
  },
  {
    key: 'web',
    label: 'Web',
    eyebrow: 'Month 7 — Web',
    headline: 'Speed & conversion',
    sub: 'CWV passing, CVR up',
    metric: { from: 1.4, to: 3.9, suffix: '% CVR', decimals: 1 },
    color: '#7B3DB8',
  },
  {
    key: 'email',
    label: 'Email',
    eyebrow: 'Month 12 — Email',
    headline: 'Automated revenue',
    sub: 'Flows running on autopilot',
    metric: { from: 89, to: 370, prefix: '$', suffix: 'K' },
    color: '#F1C518',
  },
];

// Easing — match brand
const easeOut = (t) => 1 - Math.pow(1 - t, 3);
const easeInOut = (t) => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;

// Revenue curve data — sampled across all 5 stages, exponential growth feel
function curvePoints(progress) {
  // progress 0..1 across the whole story
  const pts = [];
  const N = 60;
  for (let i = 0; i < N; i++) {
    const x = i / (N - 1);
    if (x > progress) break;
    // exponential-ish curve with a bit of organic wobble
    const wobble = Math.sin(x * 14) * 0.012 + Math.sin(x * 33) * 0.006;
    const y = Math.pow(x, 1.7) * 0.92 + wobble;
    pts.push([x, y]);
  }
  return pts;
}

function pathFromPoints(points, w, h, padX, padY) {
  if (points.length < 2) return '';
  const innerW = w - padX * 2;
  const innerH = h - padY * 2;
  const xy = points.map(([x, y]) => [padX + x * innerW, padY + (1 - y) * innerH]);
  let d = `M ${xy[0][0].toFixed(2)} ${xy[0][1].toFixed(2)}`;
  for (let i = 1; i < xy.length; i++) {
    const [px, py] = xy[i - 1];
    const [cx, cy] = xy[i];
    const mx = (px + cx) / 2;
    d += ` Q ${px.toFixed(2)} ${py.toFixed(2)} ${mx.toFixed(2)} ${((py + cy) / 2).toFixed(2)}`;
    d += ` T ${cx.toFixed(2)} ${cy.toFixed(2)}`;
  }
  return d;
}

function fillPathFromPoints(points, w, h, padX, padY) {
  if (points.length < 2) return '';
  const linePath = pathFromPoints(points, w, h, padX, padY);
  const lastX = padX + points[points.length - 1][0] * (w - padX * 2);
  const firstX = padX + points[0][0] * (w - padX * 2);
  return `${linePath} L ${lastX.toFixed(2)} ${h - padY} L ${firstX.toFixed(2)} ${h - padY} Z`;
}

function format(n, p) {
  const v = p.decimals ? n.toFixed(p.decimals) : Math.round(n);
  return `${p.prefix || ''}${v}${p.suffix || ''}`;
}

// ───────────────────────── Stage scene components ─────────────────────────

function SeoScene({ t }) {
  // t: 0..1 within stage
  const positions = [4, 3, 2, 1, 1, 1];
  const idx = Math.min(positions.length - 1, Math.floor(t * positions.length));
  const rank = positions[idx];
  return (
    <div className="hs-scene hs-seo">
      <div className="hs-search-bar">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
        </svg>
        <span className="hs-search-typed">
          {"\"best digital marketing agency\"".slice(0, Math.floor(33 * Math.min(1, t * 1.4)))}
          <span className="hs-cursor" />
        </span>
      </div>
      <ul className="hs-results">
        {[0, 1, 2, 3].map((i) => {
          const isUs = (rank - 1) === i;
          return (
            <li key={i} className={isUs ? 'hs-result hs-result-us' : 'hs-result'}>
              <span className="hs-result-fav" />
              <span className="hs-result-lines">
                <span className="hs-line hs-line-1" />
                <span className="hs-line hs-line-2" />
              </span>
              {isUs && <span className="hs-result-tag">YOU</span>}
            </li>
          );
        })}
      </ul>
    </div>
  );
}

function AdsScene({ t }) {
  // CTR rising, impressions filling
  const ctr = 1.2 + (4.8 - 1.2) * easeOut(t);
  const bars = [
    [0.15, 0.25, 0.35, 0.55, 0.45, 0.7, 0.65, 0.85, 0.78, 0.95],
  ][0];
  return (
    <div className="hs-scene hs-ads">
      <div className="hs-ads-head">
        <span className="hs-ads-label">Campaign · Conversions</span>
        <span className="hs-ads-roas">{ctr.toFixed(1)}× ROAS</span>
      </div>
      <div className="hs-ads-bars">
        {bars.map((b, i) => {
          const localT = Math.max(0, Math.min(1, t * 1.3 - i * 0.05));
          const h = b * 100 * easeOut(localT);
          return (
            <span key={i} className="hs-ads-bar" style={{ height: `${h}%` }}>
              <span className="hs-ads-bar-fill" style={{ height: '100%' }} />
            </span>
          );
        })}
      </div>
      <div className="hs-ads-x">
        <span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span>
      </div>
    </div>
  );
}

function SocialScene({ t }) {
  // Followers ticking up; small profile rows appearing
  const N = 6;
  const visible = Math.floor(N * Math.min(1, t * 1.1));
  return (
    <div className="hs-scene hs-social">
      <div className="hs-social-head">
        <span className="hs-social-handle">@yourbrand</span>
        <span className="hs-social-count">
          {(1.2 + (14.6 - 1.2) * easeOut(t)).toFixed(1)}K <em>followers</em>
        </span>
      </div>
      <ul className="hs-social-feed">
        {Array.from({ length: N }).map((_, i) => (
          <li
            key={i}
            className={i < visible ? 'hs-social-row in' : 'hs-social-row'}
            style={{ transitionDelay: `${i * 60}ms` }}
          >
            <span className="hs-avatar" data-i={i} />
            <span className="hs-social-lines">
              <span className="hs-line hs-line-1" />
              <span className="hs-line hs-line-2" />
            </span>
            <span className="hs-social-heart">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 21s-7-4.5-9.5-9C.5 8 3 4 7 4c2 0 3.5 1 5 3 1.5-2 3-3 5-3 4 0 6.5 4 4.5 8C19 16.5 12 21 12 21z"/></svg>
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function WebScene({ t }) {
  // Performance gauges ramping up
  const lcp = 5.2 - (5.2 - 1.8) * easeOut(t); // seconds, lower is better
  const cvr = 1.4 + (3.9 - 1.4) * easeOut(t); // percent
  const score = 38 + (96 - 38) * easeOut(t);  // perf score
  return (
    <div className="hs-scene hs-web">
      <div className="hs-web-head">
        <span className="hs-dot dot-r" />
        <span className="hs-dot dot-y" />
        <span className="hs-dot dot-g" />
        <span className="hs-web-url">yourbrand.com</span>
      </div>
      <div className="hs-web-body">
        <div className="hs-gauge">
          <svg viewBox="0 0 120 60" width="100%">
            <path d="M10,55 A50,50 0 0 1 110,55" fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="6" strokeLinecap="round"/>
            <path
              d="M10,55 A50,50 0 0 1 110,55"
              fill="none" stroke="#F1C518" strokeWidth="6" strokeLinecap="round"
              strokeDasharray="157"
              strokeDashoffset={157 - 157 * (score / 100)}
              style={{ transition: 'stroke-dashoffset 80ms linear' }}
            />
          </svg>
          <div className="hs-gauge-val">{Math.round(score)}</div>
          <div className="hs-gauge-label">Performance</div>
        </div>
        <div className="hs-web-stats">
          <div className="hs-web-stat">
            <span className="hs-web-stat-label">LCP</span>
            <span className="hs-web-stat-val good">{lcp.toFixed(1)}s</span>
          </div>
          <div className="hs-web-stat">
            <span className="hs-web-stat-label">CVR</span>
            <span className="hs-web-stat-val">{cvr.toFixed(1)}%</span>
          </div>
          <div className="hs-web-stat">
            <span className="hs-web-stat-label">CLS</span>
            <span className="hs-web-stat-val good">0.04</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function EmailScene({ t }) {
  const nodes = [
    { x: 12, y: 18, label: 'Welcome' },
    { x: 50, y: 14, label: 'Educate' },
    { x: 86, y: 22, label: 'Offer' },
    { x: 30, y: 60, label: 'Win-back' },
    { x: 70, y: 64, label: 'Loyal' },
  ];
  const lines = [
    [0, 1], [1, 2], [1, 3], [3, 4], [2, 4],
  ];
  return (
    <div className="hs-scene hs-email">
      <span className="hs-email-eyebrow">Automation flow</span>
      <svg viewBox="0 0 100 80" className="hs-email-svg" preserveAspectRatio="none">
        {lines.map(([a, b], i) => {
          const A = nodes[a], B = nodes[b];
          const localT = Math.max(0, Math.min(1, t * 1.4 - i * 0.08));
          return (
            <line
              key={i}
              x1={A.x} y1={A.y} x2={A.x + (B.x - A.x) * localT} y2={A.y + (B.y - A.y) * localT}
              stroke="rgba(241,197,24,0.55)" strokeWidth="0.6" strokeDasharray="1.4 1.4" strokeLinecap="round"
            />
          );
        })}
        {nodes.map((n, i) => {
          const localT = Math.max(0, Math.min(1, t * 1.6 - i * 0.12));
          return (
            <g key={i} style={{ opacity: localT }}>
              <circle cx={n.x} cy={n.y} r="3.4" fill="#F1C518" />
              <circle cx={n.x} cy={n.y} r="3.4" fill="none" stroke="#F1C518" strokeOpacity="0.3" strokeWidth="3" />
            </g>
          );
        })}
        {/* pulse traveling on edge 1->2 */}
        {(() => {
          const pulseT = (t * 1.2) % 1;
          const A = nodes[1], B = nodes[2];
          if (t < 0.4) return null;
          return (
            <circle
              cx={A.x + (B.x - A.x) * pulseT}
              cy={A.y + (B.y - A.y) * pulseT}
              r="1.6" fill="#fff"
            />
          );
        })()}
      </svg>
      <div className="hs-email-stats">
        <div className="hs-email-stat">
          <span className="num">{Math.round(38 + 24 * easeOut(t))}%</span>
          <span className="lbl">Open</span>
        </div>
        <div className="hs-email-stat">
          <span className="num">{(2.4 + 8.6 * easeOut(t)).toFixed(1)}%</span>
          <span className="lbl">CTR</span>
        </div>
        <div className="hs-email-stat">
          <span className="num">${Math.round(1.2 + 11.8 * easeOut(t))}K</span>
          <span className="lbl">Revenue</span>
        </div>
      </div>
    </div>
  );
}

const SCENES = { seo: SeoScene, ads: AdsScene, social: SocialScene, web: WebScene, email: EmailScene };

// ───────────────────────── Main component ─────────────────────────

function HeroStory({ speed = 1, autoplay = true }) {
  const [stageIdx, setStageIdx] = useState(0);
  const [stageT, setStageT] = useState(0);  // 0..1 progress within current stage
  const [overallT, setOverallT] = useState(0); // 0..1 progress across all stages
  const [paused, setPaused] = useState(!autoplay);
  const rafRef = useRef(null);
  const lastTickRef = useRef(0);

  const STAGE_MS = 3200 / Math.max(0.25, speed);

  // Reset when autoplay flips back on, or speed changes meaningfully
  useEffect(() => { setPaused(!autoplay); }, [autoplay]);

  useEffect(() => {
    function tick(now) {
      if (lastTickRef.current === 0) lastTickRef.current = now;
      const dt = now - lastTickRef.current;
      lastTickRef.current = now;
      if (!paused) {
        setStageT((prev) => {
          const next = prev + dt / STAGE_MS;
          if (next >= 1) {
            setStageIdx((s) => {
              const ns = (s + 1) % STAGES.length;
              if (ns === 0) setOverallT(0);
              return ns;
            });
            return 0;
          }
          return next;
        });
        setOverallT((prev) => {
          const inc = dt / (STAGE_MS * STAGES.length);
          const n = prev + inc;
          return n > 1 ? 1 : n;
        });
      }
      rafRef.current = requestAnimationFrame(tick);
    }
    rafRef.current = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(rafRef.current);
      lastTickRef.current = 0;
    };
  }, [paused, STAGE_MS]);

  const stage = STAGES[stageIdx];
  const Scene = SCENES[stage.key];

  // Curve uses overallT but also adds per-stage smooth fill so it "draws" live
  const liveProgress = Math.min(1, overallT + (stageT / STAGES.length) * 0.6);
  const points = curvePoints(liveProgress);
  const W = 460, H = 90, PX = 8, PY = 10;
  const linePath = pathFromPoints(points, W, H, PX, PY);
  const fillPath = fillPathFromPoints(points, W, H, PX, PY);
  const headPt = points[points.length - 1];
  const headXY = headPt
    ? [PX + headPt[0] * (W - PX * 2), PY + (1 - headPt[1]) * (H - PY * 2)]
    : null;

  // Metric counter for current stage
  const m = stage.metric;
  const metricVal = m.from + (m.to - m.from) * easeOut(stageT);

  return (
    <div className="hs-stage">
      <div className="hs-bg-grid" aria-hidden="true" />
      <div className="hs-bg-glow" aria-hidden="true" />

      {/* Stage indicator pill row */}
      <div className="hs-tabs" role="tablist">
        {STAGES.map((s, i) => (
          <button
            key={s.key}
            role="tab"
            aria-selected={i === stageIdx}
            className={i === stageIdx ? 'hs-tab on' : 'hs-tab'}
            onClick={() => { setStageIdx(i); setStageT(0); setOverallT(i / STAGES.length); }}
          >
            <span className="hs-tab-dot" />
            <span className="hs-tab-label">{s.label}</span>
          </button>
        ))}
      </div>

      {/* Scene area */}
      <div className="hs-scene-wrap">
        <div key={stage.key} className="hs-scene-card">
          <span className="hs-eyebrow">{stage.eyebrow}</span>
          <div className="hs-scene-inner">
            <Scene t={stageT} />
          </div>
          <div className="hs-scene-foot">
            <span className="hs-headline">{stage.headline}</span>
            <span className="hs-metric">{format(metricVal, m)}</span>
          </div>
        </div>
      </div>

      {/* Cumulative revenue curve at the bottom */}
      <div className="hs-curve" aria-hidden="true">
        <div className="hs-curve-head">
          <span className="hs-curve-eyebrow">Cumulative revenue</span>
          <span className="hs-curve-val">${Math.round(89 + (370 - 89) * easeOut(overallT))}K</span>
        </div>
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="hs-curve-svg">
          <defs>
            <linearGradient id="hs-curve-fill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#F1C518" stopOpacity="0.35"/>
              <stop offset="1" stopColor="#F1C518" stopOpacity="0"/>
            </linearGradient>
          </defs>
          <path d={fillPath} fill="url(#hs-curve-fill)" />
          <path d={linePath} fill="none" stroke="#F1C518" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          {headXY && (
            <g>
              <circle cx={headXY[0]} cy={headXY[1]} r="6" fill="#F1C518" opacity="0.18"/>
              <circle cx={headXY[0]} cy={headXY[1]} r="3" fill="#F1C518"/>
            </g>
          )}
        </svg>
      </div>

      {/* Play / pause control */}
      <button
        type="button"
        className="hs-play"
        aria-label={paused ? 'Play animation' : 'Pause animation'}
        onClick={() => setPaused(p => !p)}
      >
        {paused ? (
          <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
        ) : (
          <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>
        )}
      </button>
    </div>
  );
}

window.HeroStory = HeroStory;
