/* global React */
/* Animated dashboard preview section for the marketing page.
   Renders a scaled-down replica of the real dashboard with:
   - KPI counters that animate up on scroll-in
   - A sparkline that draws itself
   - An incoming conversation that slides into the inbox
   - An "AI suggested reply" that fades in
   - A volume bar chart that grows from zero
*/
const { useState: useStateDP, useEffect: useEffectDP, useRef: useRefDP } = React;

/* IntersectionObserver — fire `onEnter` exactly once when 30% visible */
function useInView(threshold = 0.25) {
  const ref = useRefDP(null);
  const [seen, setSeen] = useStateDP(false);
  useEffectDP(() => {
    const el = ref.current;
    if (!el || seen) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { setSeen(true); io.disconnect(); }
        });
      },
      { threshold }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [seen, threshold]);
  return [ref, seen];
}

/* Animated number counter, eases out */
function useCounter(target, active, duration = 1200) {
  const [val, setVal] = useStateDP(0);
  useEffectDP(() => {
    if (!active) return;
    let raf;
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setVal(target * eased);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, active, duration]);
  return val;
}

function KpiCounter({ value, prefix = "", suffix = "", decimals = 0, active, em = false, delay = 0 }) {
  const [go, setGo] = useStateDP(false);
  useEffectDP(() => {
    if (!active) return;
    const id = setTimeout(() => setGo(true), delay);
    return () => clearTimeout(id);
  }, [active, delay]);
  const v = useCounter(value, go);
  const formatted = decimals === 0
    ? Math.round(v).toLocaleString()
    : v.toFixed(decimals);
  return (
    <span>{prefix}{em ? <em>{formatted}</em> : formatted}{suffix}</span>
  );
}

function Sparkline({ data, color = "var(--accent)", active, delay = 0 }) {
  const max = Math.max(...data) * 1.1;
  const min = Math.min(...data) * 0.92;
  const range = max - min || 1;
  const path = data
    .map((v, i) => `${i === 0 ? "M" : "L"} ${(i / (data.length - 1)) * 100} ${36 - ((v - min) / range) * 32}`)
    .join(" ");
  const [drawn, setDrawn] = useStateDP(false);
  useEffectDP(() => {
    if (!active) return;
    const id = setTimeout(() => setDrawn(true), delay);
    return () => clearTimeout(id);
  }, [active, delay]);
  return (
    <svg viewBox="0 0 100 40" preserveAspectRatio="none" className="dpv-spark">
      <path d={`${path} L 100 40 L 0 40 Z`} fill={color} opacity={drawn ? "0.10" : "0"} style={{ transition: "opacity 600ms 200ms" }} />
      <path
        d={path}
        fill="none"
        stroke={color}
        strokeWidth="1.6"
        vectorEffect="non-scaling-stroke"
        pathLength="1"
        strokeDasharray="1"
        strokeDashoffset={drawn ? 0 : 1}
        style={{ transition: "stroke-dashoffset 1000ms cubic-bezier(.6,.05,.2,1)" }}
      />
    </svg>
  );
}

function VolumeBars({ active }) {
  const data = [
    [42, 8], [58, 12], [51, 15], [72, 14], [63, 9], [28, 4], [22, 3],
    [66, 18], [78, 22], [71, 19], [88, 24], [81, 17], [34, 6], [31, 5],
  ];
  return (
    <div className="dpv-bars">
      {data.map(([ai, human], i) => (
        <div key={i} className="dpv-bars__col">
          <div
            className="dpv-bars__h"
            style={{
              height: active ? `${human}%` : "0%",
              transitionDelay: `${i * 35 + 200}ms`,
            }}
          ></div>
          <div
            className="dpv-bars__a"
            style={{
              height: active ? `${ai}%` : "0%",
              transitionDelay: `${i * 35}ms`,
            }}
          ></div>
        </div>
      ))}
    </div>
  );
}

const CONVS_DEMO = [
  { initials: "ML", name: "Maya Lukic",   msg: "Walk me through upgrading to Professional?",        tag: "Waiting", tagCls: "is-info", time: "14m" },
  { initials: "SR", name: "Sam Rivera",    msg: "What's your refund policy? — Got it. Thanks!",      tag: "AI · Resolved", tagCls: "is-ok", time: "32m" },
  { initials: "AK", name: "Anna Kowalski", msg: "🎤 Voice · 0:42 — Asking about Shopify integration", tag: "Open", tagCls: "is-warn", time: "1h" },
  { initials: "DM", name: "Dev Mehta",     msg: "Webhook signature mismatch — fixed by regenerating.", tag: "AI · Resolved", tagCls: "is-ok", time: "2h" },
];
const NEW_CONV = { initials: "TJ", name: "Tom Janssen", msg: "Voice replay cuts out at 30s on Safari mobile.", tag: "Open", tagCls: "is-warn", time: "now" };

function DashboardPreview({ t, accent }) {
  const [stageRef, inView] = useInView(0.2);
  const [showNew, setShowNew] = useStateDP(false);
  const [highlighted, setHighlighted] = useStateDP(null);
  const [showAI, setShowAI] = useStateDP(false);
  const [pulse, setPulse] = useStateDP(0);

  /* Choreography: once in view, run a sequence of beats */
  useEffectDP(() => {
    if (!inView) return;
    const beats = [
      [600,  () => setHighlighted("kpi")],
      [1700, () => setHighlighted("chart")],
      [3000, () => { setShowNew(true); setHighlighted("inbox"); setPulse((p) => p + 1); }],
      [4400, () => { setShowAI(true); setHighlighted("ai"); }],
      [6200, () => setHighlighted(null)],
    ];
    const ids = beats.map(([d, fn]) => setTimeout(fn, d));
    return () => ids.forEach(clearTimeout);
  }, [inView]);

  /* gentle pulse on the topbar dot */
  useEffectDP(() => {
    if (!inView) return;
    const id = setInterval(() => setPulse((p) => p + 1), 4500);
    return () => clearInterval(id);
  }, [inView]);

  const KPIS = [
    { lbl: "CONVERSATIONS · 30D", val: 1284, prefix: "",  suffix: "",   decimals: 0, em: true,  delta: "+24%",   spark: [42,55,48,67,71,82,78,91,103,98,112,124] },
    { lbl: "AI DEFLECTION",        val: 67,   prefix: "",  suffix: "%",  decimals: 0, em: false, delta: "+4 pts", spark: [54,56,58,57,60,62,61,63,65,64,66,67] },
    { lbl: "FIRST REPLY",          val: 1.4,  prefix: "",  suffix: "s",  decimals: 1, em: false, delta: "−0.3s",  spark: [2.1,2.0,1.9,1.8,1.7,1.6,1.6,1.5,1.5,1.4,1.4,1.4] },
    { lbl: "CSAT",                 val: 4.7,  prefix: "",  suffix: "",   decimals: 1, em: true,  delta: "+0.2",   spark: [4.3,4.4,4.4,4.5,4.5,4.6,4.6,4.7,4.7,4.7,4.7,4.7] },
  ];

  return (
    <section className="dpv section" id="dashboard-preview">
      <div className="container">
        <div className="how__head">
          <div>
            <span className="eyebrow">{(t && t.dashprev && t.dashprev.eyebrow) || "Your control room"}</span>
            <h2 className="display display--lg" style={{ marginTop: 18 }}>
              {(t && t.dashprev && t.dashprev.title) || "One inbox, one"} <em className="italic" style={{ color: "var(--accent)" }}>{(t && t.dashprev && t.dashprev.titleEm) || "AI teammate."}</em>
            </h2>
          </div>
          <p className="lead">{(t && t.dashprev && t.dashprev.sub) || "Praatbox handles the easy stuff and hands you everything that needs a human — with the context, the source citations, and a suggested reply ready to send."}</p>
        </div>

        <div className="dpv-frame" ref={stageRef}>
          {/* faux browser chrome */}
          <div className="dpv-chrome">
            <i></i><i></i><i></i>
            <span className="dpv-chrome__url">app.praatbox.com/dashboard</span>
            <span className="dpv-chrome__pulse" key={pulse}></span>
          </div>

          <div className="dpv-app">
            {/* sidebar */}
            <aside className="dpv-side">
              <div className="dpv-side__brand">
                <span className="nav__logo-mark"></span>
                <span className="dpv-side__word"></span>
              </div>
              <div className="dpv-side__team">
                <div className="dpv-side__team-av">G</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="dpv-side__team-name">Glodinas</div>
                  <div className="dpv-side__team-plan">PRO · TRIAL</div>
                </div>
              </div>
              <div className="dpv-side__group">Workspace</div>
              <a className="dpv-side__item is-active"><span className="dpv-side__dot is-on"></span>Overview</a>
              <a className="dpv-side__item">
                <span className="dpv-side__dot"></span>Conversations
                <span className="dpv-side__badge">{showNew ? 13 : 12}</span>
              </a>
              <a className="dpv-side__item"><span className="dpv-side__dot"></span>Knowledge</a>
              <a className="dpv-side__item"><span className="dpv-side__dot"></span>Analytics</a>
              <div className="dpv-side__group">Configure</div>
              <a className="dpv-side__item"><span className="dpv-side__dot"></span>Widget</a>
              <a className="dpv-side__item"><span className="dpv-side__dot"></span>Team</a>
              <a className="dpv-side__item"><span className="dpv-side__dot"></span>Billing</a>
              <a className="dpv-side__item"><span className="dpv-side__dot"></span>Settings</a>

              <div className="dpv-side__trial">
                <div className="dpv-side__trial-bar"><div style={{ width: inView ? "33%" : "0%", transition: "width 1400ms 600ms" }}></div></div>
                <div className="dpv-side__trial-meta">
                  <span>10 DAYS LEFT</span>
                  <span style={{ color: "var(--accent)" }}>UPGRADE →</span>
                </div>
              </div>
            </aside>

            {/* main column */}
            <div className="dpv-col">
              <div className="dpv-top">
                <div className="dpv-top__search">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
                  <span>Search conversations, customers…</span>
                  <span className="dpv-top__kbd">⌘K</span>
                </div>
                <div className="dpv-top__actions">
                  <span className="dpv-top__bell">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>
                    <span className="dpv-top__bell-dot"></span>
                  </span>
                  <span className="dpv-top__profile">
                    <span className="dpv-top__av">AV</span>
                    <span>Anouk</span>
                  </span>
                </div>
              </div>

              <div className="dpv-main">
                <div className="dpv-pagehead">
                  <h3>Good morning, <em>Anouk.</em></h3>
                  <p>184 conversations handled overnight · 12 waiting on you · CSAT 4.7</p>
                </div>

                {/* KPI strip */}
                <div className={`dpv-kpis ${highlighted === "kpi" ? "is-spot" : ""}`}>
                  {KPIS.map((k, i) => (
                    <div key={k.lbl} className="dpv-kpi" style={{ transitionDelay: `${i * 90}ms`, opacity: inView ? 1 : 0, transform: inView ? "translateY(0)" : "translateY(8px)" }}>
                      <div className="dpv-kpi__lbl">{k.lbl}</div>
                      <div className="dpv-kpi__val">
                        <KpiCounter value={k.val} prefix={k.prefix} suffix={k.suffix} decimals={k.decimals} active={inView} em={k.em} delay={i * 100} />
                      </div>
                      <div className="dpv-kpi__delta">{k.delta} vs prior 30d</div>
                      <Sparkline data={k.spark} active={inView} delay={400 + i * 90} />
                    </div>
                  ))}
                </div>

                {/* row 2: chart + inbox preview */}
                <div className="dpv-row">
                  <div className={`dpv-card dpv-chart ${highlighted === "chart" ? "is-spot" : ""}`}>
                    <div className="dpv-card__head">
                      <div>
                        <h4>Conversations · 14 days</h4>
                        <p>AI handled vs human handoff per day</p>
                      </div>
                    </div>
                    <VolumeBars active={inView} />
                    <div className="dpv-chart__legend">
                      <span><i style={{ background: "var(--accent)" }}></i>AI handled · 860</span>
                      <span><i style={{ background: "var(--ink-3, #999)" }}></i>Human · 332</span>
                      <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", color: "var(--muted)" }}>~ 142h saved</span>
                    </div>
                  </div>

                  <div className={`dpv-card dpv-inbox ${highlighted === "inbox" ? "is-spot" : ""}`}>
                    <div className="dpv-card__head">
                      <div>
                        <h4>Open inbox</h4>
                        <p>Waiting on a human</p>
                      </div>
                      <span className="dpv-pill">{showNew ? 13 : 12}</span>
                    </div>
                    <div className="dpv-conv-list">
                      {showNew && (
                        <div className="dpv-conv is-new">
                          <div className="dpv-conv__av">{NEW_CONV.initials}</div>
                          <div className="dpv-conv__body">
                            <div className="dpv-conv__name">{NEW_CONV.name}<span className="dpv-conv__live"></span></div>
                            <div className="dpv-conv__msg">{NEW_CONV.msg}</div>
                          </div>
                          <span className={`dpv-tag ${NEW_CONV.tagCls}`}>{NEW_CONV.tag}</span>
                          <span className="dpv-conv__time">{NEW_CONV.time}</span>
                        </div>
                      )}
                      {CONVS_DEMO.map((c, i) => (
                        <div key={c.name} className="dpv-conv" style={{ opacity: inView ? 1 : 0, transitionDelay: `${500 + i * 90}ms` }}>
                          <div className="dpv-conv__av">{c.initials}</div>
                          <div className="dpv-conv__body">
                            <div className="dpv-conv__name">{c.name}</div>
                            <div className="dpv-conv__msg">{c.msg}</div>
                          </div>
                          <span className={`dpv-tag ${c.tagCls}`}>{c.tag}</span>
                          <span className="dpv-conv__time">{c.time}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                {/* AI suggestion floater */}
                <div className={`dpv-ai ${showAI ? "is-on" : ""} ${highlighted === "ai" ? "is-spot" : ""}`}>
                  <div className="dpv-ai__head">
                    <span className="dpv-ai__badge">AI</span>
                    <span className="dpv-ai__title">Suggested reply for Tom</span>
                    <span className="dpv-ai__time">drafted in 1.4s</span>
                  </div>
                  <p className="dpv-ai__body">
                    "We've reproduced the Safari 30s cut-out and it's a known regression in Safari 17.4 with our voice player. We pushed a fix at 14:02 — could you reload and try again? If it's still happening, here's a workaround in the meantime…"
                  </p>
                  <div className="dpv-ai__cites">
                    <span className="dpv-cite">📄 Voice player · v2.4 release notes</span>
                    <span className="dpv-cite">📄 Help Center · Safari issues</span>
                  </div>
                  <div className="dpv-ai__actions">
                    <button className="dpv-btn dpv-btn--accent">Send reply</button>
                    <button className="dpv-btn">Edit</button>
                    <button className="dpv-btn">Reject</button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Caption strip below the frame */}
          <div className="dpv-caption">
            <div className={`dpv-caption__step ${highlighted === "kpi" ? "is-on" : ""}`}><span>01</span>Live KPIs across every channel</div>
            <div className={`dpv-caption__step ${highlighted === "chart" ? "is-on" : ""}`}><span>02</span>AI deflection trend you can defend</div>
            <div className={`dpv-caption__step ${highlighted === "inbox" ? "is-on" : ""}`}><span>03</span>Hands you only what needs you</div>
            <div className={`dpv-caption__step ${highlighted === "ai" ? "is-on" : ""}`}><span>04</span>With a reply already drafted</div>
          </div>
        </div>

        <div className="dpv-cta">
          <a href="Dashboard.html" className="btn btn--primary">Open the live dashboard <span aria-hidden>→</span></a>
          <a href="Register.html" className="btn btn--ghost">Start free trial</a>
        </div>
      </div>
    </section>
  );
}

window.DashboardPreview = DashboardPreview;
