/* ─────────────────────────────────────────────────────────────────
   CorpSol — animated dashboard mock for hero
   ───────────────────────────────────────────────────────────────── */

function QuantaDash() {
  const t = useT();
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [conv, setConv] = React.useState(18.4);
  const [callsNow, setCallsNow] = React.useState(412);
  const [leadsToday, setLeadsToday] = React.useState(247);
  const [pulse, setPulse] = React.useState(0);

  // Animate metrics ticking up / breathing
  React.useEffect(() => {
    const id = setInterval(() => {
      setPulse((p) => p + 1);
      setConv((c) => {
        const next = c + (Math.random() - 0.4) * 0.4;
        return Math.max(15.5, Math.min(22.5, next));
      });
      setCallsNow((c) => c + Math.round((Math.random() - 0.3) * 8));
      setLeadsToday((l) => l + (Math.random() > 0.65 ? 1 : 0));
    }, 1400);
    return () => clearInterval(id);
  }, []);

  React.useEffect(() => {
    const id = setInterval(() => setActiveIdx((i) => (i + 1) % 3), 3200);
    return () => clearInterval(id);
  }, []);

  // Sparkline data — generate a smooth-ish line
  const sparkPoints = React.useMemo(() => {
    const n = 28;
    let acc = 50;
    const arr = [];
    for (let i = 0; i < n; i++) {
      acc += (Math.random() - 0.45) * 8;
      acc = Math.max(20, Math.min(86, acc));
      arr.push(acc);
    }
    return arr;
  }, [pulse % 10 === 0 ? Math.floor(pulse / 10) : 0]);

  const sparkPath = (() => {
    const W = 280, H = 60;
    const dx = W / (sparkPoints.length - 1);
    let d = '';
    sparkPoints.forEach((y, i) => {
      const X = i * dx;
      const Y = H - (y / 100) * H;
      d += (i === 0 ? 'M' : 'L') + X.toFixed(1) + ',' + Y.toFixed(1) + ' ';
    });
    return d.trim();
  })();
  const sparkFill = (() => {
    const W = 280, H = 60;
    return `${sparkPath} L${W},${H} L0,${H} Z`;
  })();

  const lines = [
    { who: 'A', label: t('dash.line1'), tag: null },
    { who: 'B', label: t('dash.line2'), tag: t('dash.tag.hot') },
    { who: 'A', label: t('dash.line3'), tag: t('dash.tag.crm') },
  ];

  return (
    <div className="cs-dash" data-noncommentable="">
      {/* window chrome */}
      <div className="cs-dash-chrome">
        <div className="cs-dash-dots">
          <span style={{ background: '#ff5f57' }} />
          <span style={{ background: '#febc2e' }} />
          <span style={{ background: '#28c840' }} />
        </div>
        <div className="cs-dash-title">{t('dash.title')}</div>
        <div className="cs-dash-live">
          <span className="cs-dash-pulse" />
          {t('dash.status')}
        </div>
      </div>

      <div className="cs-dash-body">
        {/* metrics row */}
        <div className="cs-dash-metrics">
          <Metric label={t('dash.calls')} value={callsNow} format="int" />
          <Metric label={t('dash.leads')} value={leadsToday} format="int" />
          <Metric label={t('dash.conv')} value={conv} format="pct" />
          <Metric label={t('dash.sla')} value="3.45" suffix="мин" plain />
        </div>

        {/* chart card */}
        <div className="cs-dash-card cs-dash-chart">
          <div className="cs-dash-card-h">
            <span>Конверсия в лид · 24 ч</span>
            <span className="cs-dash-card-h-r">
              <span className="cs-dash-langchip">RU 64%</span>
              <span className="cs-dash-langchip">KZ 36%</span>
            </span>
          </div>
          <svg viewBox="0 0 280 60" width="100%" height="60" preserveAspectRatio="none" style={{ overflow: 'visible' }}>
            <defs>
              <linearGradient id="gradSpark" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="var(--c-accent)" stopOpacity="0.28" />
                <stop offset="100%" stopColor="var(--c-accent)" stopOpacity="0" />
              </linearGradient>
            </defs>
            <path d={sparkFill} fill="url(#gradSpark)" />
            <path d={sparkPath} fill="none" stroke="var(--c-accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            {sparkPoints.length > 0 && (
              <circle
                cx={280}
                cy={60 - (sparkPoints[sparkPoints.length - 1] / 100) * 60}
                r="4"
                fill="var(--c-accent)"
                stroke="#fff"
                strokeWidth="2"
              />
            )}
          </svg>
        </div>

        {/* transcript */}
        <div className="cs-dash-card cs-dash-trans">
          <div className="cs-dash-card-h">
            <span>{t('dash.transcript')}</span>
            <span className="cs-dash-card-h-r">
              <span className="cs-dash-langchip cs-dash-langchip--on">{t('dash.lang.ru')}</span>
              <span className="cs-dash-langchip">{t('dash.lang.kz')}</span>
            </span>
          </div>
          <div className="cs-dash-lines">
            {lines.map((l, i) => (
              <div key={i} className={'cs-dash-line ' + (i === activeIdx ? 'is-on' : '') + ' ' + (i < activeIdx ? 'is-done' : '')}>
                <span className={'cs-dash-who cs-dash-who--' + l.who.toLowerCase()}>{l.who === 'A' ? 'AI' : 'CL'}</span>
                <span className="cs-dash-text">{l.label}</span>
                {i === activeIdx && (
                  <span className="cs-dash-bars" aria-hidden="true">
                    <i style={{ animationDelay: '0s' }} />
                    <i style={{ animationDelay: '0.15s' }} />
                    <i style={{ animationDelay: '0.3s' }} />
                  </span>
                )}
                {l.tag && i <= activeIdx && (
                  <span className={'cs-dash-tag ' + (l.tag.toLowerCase().includes('crm') ? 'cs-dash-tag--ok' : 'cs-dash-tag--hot')}>
                    {l.tag}
                  </span>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* queue strip */}
        <div className="cs-dash-card cs-dash-queue">
          <div className="cs-dash-card-h">
            <span>{t('dash.queue')} · {t('dash.agents')}: 76</span>
            <span className="cs-mute" style={{ fontSize: 11 }}>обновлено сейчас</span>
          </div>
          <div className="cs-dash-q-bars">
            {Array.from({ length: 14 }).map((_, i) => {
              const h = 24 + ((Math.sin((i + pulse) * 0.55) + 1) * 16) + (i % 3) * 4;
              const on = i < 9;
              return (
                <div key={i} className={'cs-dash-q-bar ' + (on ? 'is-on' : '')}
                     style={{ height: h + 'px' }} />
              );
            })}
          </div>
        </div>
      </div>

      <style>{`
        .cs-dash {
          width: 100%;
          background: var(--c-bg);
          border-radius: 22px;
          box-shadow: var(--shadow-lg), 0 60px 80px -40px rgba(10, 31, 68, 0.35);
          overflow: hidden;
          font-family: var(--font-body);
          color: var(--c-ink);
          border: 1px solid var(--c-line);
        }
        [data-radius="sharp"] .cs-dash { border-radius: 6px; }
        [data-radius="pill"] .cs-dash { border-radius: 32px; }

        .cs-dash-chrome {
          display: flex; align-items: center; gap: 12px;
          padding: 12px 16px;
          background: var(--c-bg-soft);
          border-bottom: 1px solid var(--c-line);
        }
        .cs-dash-dots { display: flex; gap: 6px; }
        .cs-dash-dots span { width: 11px; height: 11px; border-radius: 50%; display: block; }
        .cs-dash-title { font-size: 12px; font-weight: 600; color: var(--c-mute-2); letter-spacing: -0.005em; }
        .cs-dash-live {
          margin-left: auto;
          display: inline-flex; align-items: center; gap: 6px;
          font-size: 11px; font-weight: 600;
          color: #16a34a;
          background: rgba(22, 163, 74, 0.1);
          padding: 4px 10px; border-radius: 999px;
        }
        .cs-dash-pulse {
          width: 7px; height: 7px; background: #16a34a; border-radius: 50%;
          animation: cs-pulse 1.5s ease-in-out infinite;
        }
        @keyframes cs-pulse {
          0%, 100% { box-shadow: 0 0 0 0 rgba(22, 163, 74, 0.5); }
          70%      { box-shadow: 0 0 0 6px rgba(22, 163, 74, 0); }
        }

        .cs-dash-body { padding: 18px; display: grid; gap: 14px; }
        .cs-dash-metrics {
          display: grid; gap: 12px;
          grid-template-columns: repeat(4, 1fr);
        }
        @media (max-width: 540px) {
          .cs-dash-metrics { grid-template-columns: repeat(2, 1fr); }
        }

        .cs-dash-card {
          background: var(--c-bg-soft);
          border-radius: 14px;
          padding: 14px 16px;
        }
        [data-radius="sharp"] .cs-dash-card { border-radius: 4px; }
        [data-radius="pill"] .cs-dash-card { border-radius: 20px; }

        .cs-dash-card-h {
          display: flex; align-items: center; justify-content: space-between;
          margin-bottom: 8px;
          font-size: 11.5px; font-weight: 600;
          color: var(--c-mute);
          letter-spacing: -0.002em;
        }
        .cs-dash-card-h-r { display: inline-flex; gap: 4px; }
        .cs-dash-langchip {
          font-size: 10px; font-weight: 600;
          padding: 2px 7px; border-radius: 999px;
          background: var(--c-bg); color: var(--c-faint);
        }
        .cs-dash-langchip--on { background: var(--c-accent); color: #fff; }

        .cs-metric {
          padding: 14px 14px; border-radius: 12px;
          background: var(--c-bg-soft);
        }
        [data-radius="sharp"] .cs-metric { border-radius: 4px; }
        [data-radius="pill"] .cs-metric { border-radius: 20px; }
        .cs-metric-l { font-size: 11px; font-weight: 600; color: var(--c-faint); letter-spacing: 0.02em; text-transform: uppercase; }
        .cs-metric-v { font-family: var(--font-display); font-size: 26px; font-weight: 700; letter-spacing: -0.03em; margin-top: 4px; font-variant-numeric: tabular-nums; }
        .cs-metric-v .cs-metric-suffix { font-size: 13px; font-weight: 500; color: var(--c-mute); margin-left: 4px; }

        .cs-dash-lines { display: flex; flex-direction: column; gap: 8px; }
        .cs-dash-line {
          display: flex; align-items: center; gap: 10px;
          padding: 9px 12px;
          background: var(--c-bg);
          border-radius: 10px;
          font-size: 12.5px;
          opacity: 0.42;
          transition: opacity 0.3s var(--ease), background 0.3s var(--ease);
        }
        .cs-dash-line.is-on { opacity: 1; background: var(--c-bg); box-shadow: 0 0 0 1.5px var(--c-accent); }
        .cs-dash-line.is-done { opacity: 0.65; }
        .cs-dash-who {
          flex-shrink: 0;
          width: 26px; height: 22px; border-radius: 999px;
          font-size: 10px; font-weight: 700;
          display: inline-flex; align-items: center; justify-content: center;
          letter-spacing: 0.04em;
        }
        .cs-dash-who--a { background: var(--c-accent); color: #fff; }
        .cs-dash-who--b { background: var(--c-bg-muted); color: var(--c-mute-2); }
        .cs-dash-text { flex: 1; color: var(--c-ink-2); line-height: 1.45; }
        .cs-dash-bars { display: inline-flex; gap: 2px; align-items: flex-end; height: 14px; }
        .cs-dash-bars i {
          width: 2.5px; height: 100%; background: var(--c-accent); border-radius: 4px; display: block;
          transform-origin: bottom;
          animation: cs-bars 0.8s ease-in-out infinite;
        }
        @keyframes cs-bars {
          0%, 100% { transform: scaleY(0.35); }
          50%      { transform: scaleY(1); }
        }
        .cs-dash-tag {
          flex-shrink: 0; font-size: 10px; font-weight: 700;
          padding: 3px 8px; border-radius: 999px;
          letter-spacing: 0.02em;
          animation: cs-fade-in 0.4s var(--ease);
        }
        .cs-dash-tag--hot { background: rgba(234, 88, 12, 0.13); color: #ea580c; }
        .cs-dash-tag--ok { background: rgba(22, 163, 74, 0.13); color: #16a34a; }
        @keyframes cs-fade-in { from { opacity: 0; transform: translateX(-4px); } to { opacity: 1; transform: none; } }

        .cs-dash-q-bars { display: flex; align-items: flex-end; gap: 4px; height: 56px; }
        .cs-dash-q-bar {
          flex: 1; min-width: 4px;
          background: var(--c-bg-muted); border-radius: 4px;
          transition: height 0.6s var(--ease);
        }
        .cs-dash-q-bar.is-on { background: var(--c-accent); }

        /* on dark, lift card backgrounds */
        [data-theme="dark"] .cs-dash-card { background: #161d36; }
        [data-theme="dark"] .cs-metric { background: #161d36; }
        [data-theme="dark"] .cs-dash-line { background: #0a0e1a; }
        [data-theme="dark"] .cs-dash-q-bar { background: #1f2747; }
        [data-theme="dark"] .cs-dash-langchip { background: #0a0e1a; }
      `}</style>
    </div>
  );
}

function Metric({ label, value, format, suffix, plain }) {
  // Smoothly format numbers
  let display = value;
  if (format === 'pct') display = (typeof value === 'number' ? value.toFixed(1) : value) + '%';
  else if (format === 'int') display = typeof value === 'number' ? value.toLocaleString('ru-RU') : value;
  return (
    <div className="cs-metric">
      <div className="cs-metric-l">{label}</div>
      <div className="cs-metric-v">
        {display}
        {suffix && <span className="cs-metric-suffix">{suffix}</span>}
      </div>
    </div>
  );
}

window.QuantaDash = QuantaDash;
