/* Dashboard mock — React component */
const { useState, useEffect, useRef } = React;

const INITIAL_LEADS = [
  { name: "Martina Reyes", company: "Northwind Labs", phone: "+1 (415) 555-0119", status: "reached", duration: "3:42", outcome: "Booked demo Tue 3pm", avatar: "MR", callAt: "10:42" },
  { name: "James O'Connell", company: "Meridian Freight", phone: "+44 20 7946 0022", status: "calling", duration: "1:18", outcome: "—", avatar: "JO", callAt: "10:44" },
  { name: "Priya Venkat", company: "Lumen AI", phone: "+1 (212) 555-0142", status: "callback", duration: "0:58", outcome: "Asked to call back 4pm", avatar: "PV", callAt: "10:39" },
  { name: "Tomás Herrera", company: "Ribera & Co", phone: "+34 91 555 0167", status: "voicemail", duration: "0:24", outcome: "Left message", avatar: "TH", callAt: "10:37" },
  { name: "Anna Kowalski", company: "Blueprint Studio", phone: "+48 22 555 0198", status: "reached", duration: "4:11", outcome: "Not interested", avatar: "AK", callAt: "10:31" },
  { name: "Derek Huang", company: "Parallax Retail", phone: "+1 (650) 555-0134", status: "queued", duration: "—", outcome: "—", avatar: "DH", callAt: "—" },
  { name: "Sofia Mancini", company: "Atlas Robotics", phone: "+39 06 555 0155", status: "reached", duration: "2:47", outcome: "Sent info pack", avatar: "SM", callAt: "10:28" },
  { name: "Noah Patel", company: "Ember Analytics", phone: "+1 (737) 555-0171", status: "queued", duration: "—", outcome: "—", avatar: "NP", callAt: "—" },
];

const STATUS_LABEL = {
  reached: "Reached",
  calling: "Calling",
  callback: "Callback",
  voicemail: "Voicemail",
  queued: "Queued",
  failed: "Failed",
};

function StatusPill({ status }) {
  const style = {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "3px 9px",
    borderRadius: 100,
    fontSize: 11.5,
    fontWeight: 500,
    background: `var(--status-${status}-soft)`,
    color: `var(--status-${status})`,
    whiteSpace: "nowrap",
    fontFamily: "var(--font-sans)",
  };
  const queued = {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "3px 9px",
    borderRadius: 100,
    fontSize: 11.5,
    fontWeight: 500,
    background: "var(--bg-alt)",
    color: "var(--text-muted)",
    border: "1px solid var(--border)",
    whiteSpace: "nowrap",
    fontFamily: "var(--font-sans)",
  };
  const failed = { ...style };
  const isCalling = status === "calling";
  return (
    <span style={status === "queued" ? queued : status === "failed" ? failed : style}>
      <span style={{
        width: 6, height: 6, borderRadius: "50%",
        background: status === "queued" ? "var(--text-subtle)" : `var(--status-${status})`,
        animation: isCalling ? "pulse-dot 1.4s ease-in-out infinite" : "none",
      }} />
      {STATUS_LABEL[status]}
    </span>
  );
}

function Sparkline() {
  // Mini animated call-volume sparkline
  const points = [12, 18, 15, 22, 28, 24, 32, 30, 38, 34, 42, 39, 46, 52, 48, 56];
  const max = Math.max(...points);
  const w = 140, h = 36;
  const path = points.map((p, i) => {
    const x = (i / (points.length - 1)) * w;
    const y = h - (p / max) * h * 0.9 - 2;
    return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  const area = `${path} L${w},${h} L0,${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: "block" }}>
      <path d={area} fill="var(--accent-soft)" />
      <path d={path} stroke="var(--accent)" strokeWidth="1.5" fill="none" strokeLinejoin="round" />
    </svg>
  );
}

function Waveform({ active }) {
  const bars = 18;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 2, height: 18 }}>
      {Array.from({ length: bars }).map((_, i) => (
        <span key={i} style={{
          width: 2,
          height: active ? `${4 + Math.abs(Math.sin((i + 1) * 0.7)) * 14}px` : "3px",
          background: active ? "var(--status-calling)" : "var(--border-strong)",
          borderRadius: 1,
          animation: active ? `wave-${i % 4} 0.9s ease-in-out infinite` : "none",
          animationDelay: `${i * 60}ms`,
        }} />
      ))}
    </div>
  );
}

function Dashboard() {
  const [leads, setLeads] = useState(INITIAL_LEADS);
  const [tick, setTick] = useState(0);
  const [elapsed, setElapsed] = useState({});

  // Live tick: advance calling durations, occasionally transition statuses
  useEffect(() => {
    const id = setInterval(() => {
      setTick(t => t + 1);
      setLeads(prev => prev.map((l, idx) => {
        if (l.status === "calling") {
          // Parse current duration
          const [m, s] = l.duration.split(":").map(Number);
          const total = m * 60 + s + 1;
          const nm = Math.floor(total / 60), ns = total % 60;
          const newDur = `${nm}:${ns.toString().padStart(2, "0")}`;
          return { ...l, duration: newDur };
        }
        return l;
      }));
    }, 1000);
    return () => clearInterval(id);
  }, []);

  // Status transitions every ~7 seconds
  useEffect(() => {
    const id = setInterval(() => {
      setLeads(prev => {
        const next = [...prev];
        // Find a calling lead to resolve
        const callingIdx = next.findIndex(l => l.status === "calling");
        if (callingIdx >= 0) {
          const outcomes = [
            { status: "reached", outcome: "Qualified — sending calendar link" },
            { status: "callback", outcome: "Asked to call back tomorrow" },
            { status: "voicemail", outcome: "Left message" },
          ];
          const pick = outcomes[Math.floor(Math.random() * outcomes.length)];
          next[callingIdx] = { ...next[callingIdx], ...pick };
        }
        // Promote a queued lead to calling
        const queuedIdx = next.findIndex(l => l.status === "queued");
        if (queuedIdx >= 0) {
          next[queuedIdx] = { ...next[queuedIdx], status: "calling", duration: "0:02", callAt: new Date().toTimeString().slice(0, 5) };
        }
        return next;
      });
    }, 7000);
    return () => clearInterval(id);
  }, []);

  const counts = leads.reduce((acc, l) => {
    acc[l.status] = (acc[l.status] || 0) + 1;
    return acc;
  }, {});
  const reached = counts.reached || 0;
  const total = leads.length;
  const contactRate = Math.round((reached / total) * 100);

  return (
    <div className="dash">
      {/* Chrome */}
      <div className="dash-chrome">
        <div className="dash-traffic">
          <span></span><span></span><span></span>
        </div>
        <div className="dash-url">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
          app.ringlist.io/campaigns/q2-outbound
        </div>
        <div className="dash-chrome-actions">
          <span className="dash-dot-live"><span></span>Live</span>
        </div>
      </div>

      {/* Sidebar + main */}
      <div className="dash-body">
        <aside className="dash-side">
          <div className="dash-side-header">
            <div className="logo" style={{ fontSize: 14 }}>
              <svg className="logo-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="7" opacity="0.55"/><circle cx="12" cy="12" r="10.5" opacity="0.25"/></svg>
              <span>Ringlist</span>
            </div>
          </div>
          <nav className="dash-nav">
            <a className="active"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>Campaigns</a>
            <a><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>Leads</a>
            <a><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>Results</a>
            <a><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>Settings</a>
          </nav>
          <div className="dash-credit">
            <div className="dash-credit-row">
              <span style={{ color: "var(--text-muted)", fontSize: 11 }}>Credit</span>
              <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>€42.80</span>
            </div>
            <div className="dash-credit-bar"><span style={{ width: "68%" }}></span></div>
          </div>
        </aside>

        <main className="dash-main">
          <div className="dash-header">
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                <h3 style={{ fontSize: 18, fontFamily: "var(--font-display)", margin: 0 }}>Q2 Outbound — Northeast</h3>
                <span className="dash-tag">Running</span>
              </div>
              <p style={{ fontSize: 12.5, color: "var(--text-muted)", margin: 0 }}>Started 42 min ago · 247 leads · Agent: Ava (neutral, friendly)</p>
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="dash-btn-ghost">Pause</button>
              <button className="dash-btn-primary">Export</button>
            </div>
          </div>

          {/* Stat cards */}
          <div className="dash-stats">
            <div className="dash-stat">
              <div className="dash-stat-label">Calls placed</div>
              <div className="dash-stat-value">142<span>/247</span></div>
              <Sparkline />
            </div>
            <div className="dash-stat">
              <div className="dash-stat-label">Contact rate</div>
              <div className="dash-stat-value">{contactRate}<span>%</span></div>
              <div className="dash-stat-bar">
                <span style={{ width: `${contactRate}%`, background: "var(--status-reached)" }}></span>
              </div>
            </div>
            <div className="dash-stat">
              <div className="dash-stat-label">Avg duration</div>
              <div className="dash-stat-value">2<span>:41</span></div>
              <div style={{ fontSize: 11, color: "var(--status-reached)", marginTop: 8 }}>↑ 12s vs last run</div>
            </div>
            <div className="dash-stat">
              <div className="dash-stat-label">Minutes used</div>
              <div className="dash-stat-value">57<span>.2</span></div>
              <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 8 }}>€8.58 of €10.00 top-up</div>
            </div>
          </div>

          {/* Lead table */}
          <div className="dash-table">
            <div className="dash-table-head">
              <div className="dash-th" style={{ flex: "1 1 28%" }}>Lead</div>
              <div className="dash-th" style={{ flex: "0 0 130px" }}>Status</div>
              <div className="dash-th" style={{ flex: "1 1 30%" }}>Outcome</div>
              <div className="dash-th" style={{ flex: "0 0 70px", textAlign: "right" }}>Time</div>
              <div className="dash-th" style={{ flex: "0 0 90px", textAlign: "right" }}>Duration</div>
            </div>
            <div className="dash-table-body">
              {leads.map((l, i) => (
                <div key={i} className={`dash-row ${l.status === "calling" ? "active" : ""}`}>
                  <div className="dash-td" style={{ flex: "1 1 28%", display: "flex", alignItems: "center", gap: 10 }}>
                    <div className="dash-avatar">{l.avatar}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.company}</div>
                    </div>
                  </div>
                  <div className="dash-td" style={{ flex: "0 0 130px" }}>
                    <StatusPill status={l.status} />
                  </div>
                  <div className="dash-td" style={{ flex: "1 1 30%", fontSize: 12.5, color: l.outcome === "—" ? "var(--text-subtle)" : "var(--text-muted)" }}>
                    {l.status === "calling" ? <Waveform active={true} /> : l.outcome}
                  </div>
                  <div className="dash-td mono" style={{ flex: "0 0 70px", textAlign: "right", fontSize: 12, color: "var(--text-muted)" }}>
                    {l.callAt}
                  </div>
                  <div className="dash-td mono" style={{ flex: "0 0 90px", textAlign: "right", fontSize: 12, color: l.status === "calling" ? "var(--status-calling)" : "var(--text-muted)", fontWeight: l.status === "calling" ? 500 : 400 }}>
                    {l.duration}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

window.RinglistDashboard = Dashboard;
