// ─── Reusable components for the LumiSkin landing page ───────────────────

const { useState, useEffect, useMemo, useRef } = React;

// ─── Sparkline for ARIA outcome traces ───────────────────────────────────
function Sparkline({ data, baseline, unit, w = 220, h = 64, color = 'var(--wine)', dir = 'ltr' }) {
  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = Math.max(1, max - min);
  const pad = 4;
  const stepX = (w - pad * 2) / (data.length - 1);
  // For RTL we mirror the x axis so the most recent point sits on the left
  const xFor = (i) => dir === 'rtl' ? w - pad - i * stepX : pad + i * stepX;
  const yFor = (v) => h - pad - ((v - min) / range) * (h - pad * 2);
  const pts = data.map((v, i) => [xFor(i), yFor(v)]);
  const linePath = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0] + ',' + p[1]).join(' ');
  const lastX = pts[pts.length - 1][0];
  const firstX = pts[0][0];
  const baselineY = yFor(baseline);
  const areaPath =
    linePath +
    ` L${lastX},${h - pad} L${firstX},${h - pad} Z`;
  const lastPt = pts[pts.length - 1];

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" style={{ display: 'block' }}>
      <defs>
        <linearGradient id={`grad-${baseline}-${data[0]}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.18" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <line x1={pad} x2={w - pad} y1={baselineY} y2={baselineY}
        stroke={color} strokeOpacity="0.25" strokeDasharray="2 3" strokeWidth="1" />
      <path d={areaPath} fill={`url(#grad-${baseline}-${data[0]})`} />
      <path d={linePath} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map(([x, y], i) => (
        <circle key={i} cx={x} cy={y} r={i === pts.length - 1 ? 3 : 0} fill={color} />
      ))}
      <circle cx={lastPt[0]} cy={lastPt[1]} r="6" fill="none" stroke={color} strokeOpacity="0.25" />
    </svg>
  );
}

// ─── Channel chip ────────────────────────────────────────────────────────
const CHANNEL_ICONS = {
  WA: '✿', SMS: '✦', IG: '◐', TG: '✈', EM: '✉', WC: '◇', WW: '◉', SL: '#', DC: '◆',
};

function ChannelChip({ k, name, note, large = false }) {
  return (
    <div className={'lk-chip ' + (large ? 'lk-chip-lg' : '')}>
      <span className="lk-chip-glyph" aria-hidden="true">{CHANNEL_ICONS[k] || '•'}</span>
      <div className="lk-chip-body">
        <div className="lk-chip-name">{name}</div>
        {note && <div className="lk-chip-note">{note}</div>}
      </div>
    </div>
  );
}

// ─── Agent card ──────────────────────────────────────────────────────────
function AgentCard({ agent, t, lang, dir, idx, accent }) {
  const role = agent.role[lang] || agent.role.en;
  const bio = agent.bio[lang] || agent.bio.en;
  const metricLabel = agent.metric.label[lang] || agent.metric.label.en;
  const secondaryLabel = agent.secondary.l[lang] || agent.secondary.l.en;

  // Direction-aware metric color: green-ish positive for + and refund index dropping
  const isPositiveDir = ['+', '%', '€'].some(s => agent.metric.value.includes(s)) && !agent.metric.value.includes('−');
  const metricColor = agent.metric.value.includes('−') ? 'var(--wine)' : 'var(--wine)';

  return (
    <article className="lk-agent" style={{ '--agent-i': idx }}>
      <header className="lk-agent-head">
        <div className="lk-agent-id">
          <span className="lk-agent-seat">{String(idx + 1).padStart(2, '0')}</span>
          <span className="lk-agent-divider" />
          <span className="lk-agent-hired">
            <span className="lk-agent-hired-lbl">{t.bench.hiredOn}</span>
            <span className="lk-agent-hired-date">{agent.hired}</span>
          </span>
        </div>
        <div className="lk-agent-channels" aria-hidden="true">
          {agent.channels.map(c => (
            <span key={c} className="lk-agent-channel" title={c}>{CHANNEL_ICONS[c]}</span>
          ))}
        </div>
      </header>

      <div className="lk-agent-name-row">
        <h3 className="lk-agent-name">{agent.name}</h3>
        <div className="lk-agent-role">{role}</div>
      </div>

      <p className="lk-agent-bio">{bio}</p>

      <div className="lk-agent-metric">
        <div className="lk-agent-metric-big" style={{ color: metricColor }}>
          {agent.metric.value}
        </div>
        <div className="lk-agent-metric-lbl">
          <div className="lk-agent-metric-lbl-main">{metricLabel}</div>
          <div className="lk-agent-metric-lbl-vs">{t.bench.vs}</div>
        </div>
      </div>

      <div className="lk-agent-trace">
        <div className="lk-agent-trace-head">
          <span>{t.bench.trace}</span>
          <span className="lk-agent-trace-second">{agent.secondary.v} · {secondaryLabel}</span>
        </div>
        <Sparkline data={agent.trace} baseline={agent.baseline} unit={agent.unit} dir={dir} color="var(--wine)" />
      </div>
    </article>
  );
}

// ─── Tiny logo mark (inline SVG echo of the photo) — used for badges ─────
function Mark({ size = 24 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" fill="none" aria-hidden="true">
      <circle cx="24" cy="24" r="23" stroke="currentColor" strokeWidth="1" opacity="0.35" />
      <path d="M14 28 Q 24 36 34 28" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" />
      <ellipse cx="18" cy="20" rx="3.5" ry="1.5" fill="currentColor" opacity="0.8" />
      <ellipse cx="30" cy="20" rx="3.5" ry="1.5" fill="currentColor" opacity="0.8" />
    </svg>
  );
}

Object.assign(window, { Sparkline, ChannelChip, AgentCard, Mark, CHANNEL_ICONS });

// ─── Live ARIA Orchestration console ─────────────────────────────────────
// Plays a sequence of customer scenarios. Each scenario has:
//   1. an incoming customer message (rendered in their language)
//   2. ZARA triage event (language + intent)
//   3. specialist agent event(s)
//   4. an outcome metric
// Steps reveal one at a time on a timer, then the scenario rotates.

const AGENT_HUES = {
  Z: 'var(--wine)',     // ZARA — triage
  N: 'var(--wine)',     // NOOR
  S: 'var(--wine-2)',   // SAJA
  L: 'var(--lip)',      // LAYLA
  A: 'var(--wine-2)',   // AMINE
  R: 'var(--gold)',     // RANIA
  K: 'var(--wine-dark)',// KENZA
};

function LiveOpsTicker() {
  // Subtly ticking live numbers so the console feels alive.
  const [active, setActive] = useState(247);
  const [ttrSec, setTtrSec] = useState(192); // 3m 12s
  useEffect(() => {
    const id = setInterval(() => {
      setActive(a => Math.max(220, Math.min(280, a + (Math.random() > 0.55 ? 1 : -1))));
      setTtrSec(s => Math.max(150, Math.min(240, s + (Math.random() > 0.5 ? 1 : -1))));
    }, 2400);
    return () => clearInterval(id);
  }, []);
  const fmt = (s) => `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;
  return (
    <div className="lk-ops-ticker">
      <div className="lk-ops-cell">
        <div className="lk-ops-cell-n tnum">{active}</div>
        <div className="lk-ops-cell-l">active</div>
      </div>
      <div className="lk-ops-cell">
        <div className="lk-ops-cell-n tnum">7<span className="lk-ops-cell-faint">/7</span></div>
        <div className="lk-ops-cell-l">agents</div>
      </div>
      <div className="lk-ops-cell">
        <div className="lk-ops-cell-n tnum">{fmt(ttrSec)}</div>
        <div className="lk-ops-cell-l">avg TTR</div>
      </div>
    </div>
  );
}

function LiveConsole({ t, lang, dir, speed = 1800 }) {
  const scenarios = window.SCENARIOS;
  const [sIdx, setSIdx] = useState(0);
  const [stepIdx, setStepIdx] = useState(0);
  const [phase, setPhase] = useState('enter'); // 'enter' | 'steps' | 'outcome' | 'exit'

  const scn = scenarios[sIdx];
  const totalSteps = scn.steps.length;

  // Drive the timeline.
  useEffect(() => {
    let tm;
    if (phase === 'enter') {
      // Customer message just appeared — start revealing steps after a beat.
      tm = setTimeout(() => setPhase('steps'), speed * 0.55);
    } else if (phase === 'steps') {
      if (stepIdx < totalSteps) {
        tm = setTimeout(() => setStepIdx(i => i + 1), speed);
      } else {
        tm = setTimeout(() => setPhase('outcome'), speed * 0.3);
      }
    } else if (phase === 'outcome') {
      // Hold the outcome, then exit.
      tm = setTimeout(() => setPhase('exit'), speed * 1.8);
    } else if (phase === 'exit') {
      tm = setTimeout(() => {
        setSIdx(i => (i + 1) % scenarios.length);
        setStepIdx(0);
        setPhase('enter');
      }, speed * 0.35);
    }
    return () => clearTimeout(tm);
  }, [phase, stepIdx, sIdx, speed, totalSteps, scenarios.length]);

  const visibleSteps = scn.steps.slice(0, phase === 'enter' ? 0 : Math.min(stepIdx, totalSteps));
  const showOutcome = phase === 'outcome' || phase === 'exit';
  const exiting = phase === 'exit';

  // Progress dots
  const progress = Math.min(1, (visibleSteps.length + (showOutcome ? 0.5 : 0)) / (totalSteps + 0.5));

  return (
    <div className={'lk-console ' + (exiting ? 'is-exit' : '')}>
      {/* Header */}
      <div className="lk-console-head">
        <div className="lk-console-live">
          <span className="lk-live-dot" />
          <span className="lk-live-text">LIVE · ARIA Orchestration</span>
        </div>
        <div className="lk-console-scn">
          {scenarios.map((_, i) => (
            <span key={i} className={'lk-console-scn-dot' + (i === sIdx ? ' is-on' : '')} />
          ))}
        </div>
      </div>

      <LiveOpsTicker />

      {/* Conversation */}
      <div className="lk-console-thread" key={scn.id}>
        {/* Customer message */}
        <div className="lk-msg lk-msg-customer">
          <div className="lk-msg-meta">
            <span className="lk-msg-channel" aria-hidden="true">{CHANNEL_ICONS[scn.channel]}</span>
            <span className="lk-msg-channel-name">{scn.channel}</span>
            <span className="lk-msg-divider">·</span>
            <span className="lk-msg-who">{scn.customer.name}, {scn.customer.city}</span>
            <span className="lk-msg-flag" aria-hidden="true">{scn.customer.flag}</span>
            <span className="lk-msg-divider">·</span>
            <span className="lk-msg-time tnum">{scn.customer.tz}</span>
          </div>
          <div className="lk-msg-bubble" dir={scn.msg.dir} lang={scn.msg.lang}>
            {scn.msg.text}
          </div>
          {scn.msg.lang !== lang && scn.msg.lang !== 'en' && lang === 'en' && (
            <div className="lk-msg-translation">→ {scn.msgEn}</div>
          )}
        </div>

        {/* Agent events */}
        <div className="lk-events">
          {visibleSteps.map((s, i) => (
            <div className="lk-event" key={i} style={{ '--ev-i': i }}>
              <div className="lk-event-rail">
                <div className="lk-event-avatar" style={{ background: AGENT_HUES[s.code] || 'var(--wine)' }}>
                  {s.code}
                </div>
                {i < visibleSteps.length - 1 && <div className="lk-event-line" />}
              </div>
              <div className="lk-event-body">
                <div className="lk-event-row">
                  <span className="lk-event-agent">{s.agent}</span>
                  <span className="lk-event-label">{s.label[lang] || s.label.en}</span>
                  <span className="lk-event-meta">{s.meta}</span>
                </div>
                <div className="lk-event-text">{s.line[lang] || s.line.en}</div>
              </div>
            </div>
          ))}

          {/* Typing indicator while next step is pending */}
          {phase === 'steps' && stepIdx < totalSteps && (
            <div className="lk-typing" aria-hidden="true">
              <span /><span /><span />
            </div>
          )}
        </div>

        {/* Outcome */}
        {showOutcome && (
          <div className="lk-outcome">
            <div className="lk-outcome-icon">✓</div>
            <div className="lk-outcome-body">
              <div className="lk-outcome-text">{scn.outcome[lang] || scn.outcome.en}</div>
              <div className="lk-outcome-metric tnum">{scn.accent}</div>
            </div>
          </div>
        )}
      </div>

      {/* Progress bar */}
      <div className="lk-console-progress">
        <div className="lk-console-progress-fill" style={{ width: `${progress * 100}%` }} />
      </div>

      {/* Footer — Québec line */}
      <div className="lk-console-foot">
        <div>
          <div className="lk-console-foot-tag">NEW · QUÉBEC LINE</div>
          <a className="lk-console-foot-phone tnum" href="tel:+18734466611">+1 873 446 6611</a>
        </div>
        <div className="lk-console-foot-langs">
          <span className="lk-console-foot-lang is-new">FR-CA</span>
          <span className="lk-console-foot-lang">EN</span>
          <span className="lk-console-foot-lang">AR</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LiveConsole, LiveOpsTicker, AGENT_HUES });
