/* global React, Icon */
const { useEffect: useEffectApp, useState: useStateApp } = React;

// ---- Dashboard metric formatting (live analytics) ----
function dashFormatCount(value) {
  const n = Number(value || 0);
  if (!Number.isFinite(n)) return '0';
  if (Math.abs(n) >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (Math.abs(n) >= 10000) return `${(n / 1000).toFixed(1)}k`;
  return n.toLocaleString();
}
function dashFormatDuration(ms) {
  const v = Number(ms || 0);
  if (!Number.isFinite(v) || v <= 0) return '—';
  if (v < 1000) return `${Math.round(v)}ms`;
  if (v < 60000) return `${(v / 1000).toFixed(1)}s`;
  if (v < 3600000) return `${Math.round(v / 60000)}m`;
  const h = Math.floor(v / 3600000);
  const m = Math.round((v % 3600000) / 60000);
  return m ? `${h}h ${m}m` : `${h}h`;
}
function dashFormatMetric(metric) {
  if (!metric) return '—';
  const value = Number(metric.value || 0);
  if (metric.unit === 'rate') {
    if (metric.hasDenominator === false) return '—';
    return `${(value * 100).toFixed(value < 0.1 ? 1 : 0)}%`;
  }
  if (metric.unit === 'duration_ms') {
    if (metric.hasDenominator === false) return '—';
    return dashFormatDuration(value);
  }
  if (metric.unit === 'currency_usd') return value >= 1 ? `$${value.toFixed(2)}` : `$${value.toFixed(4)}`;
  return dashFormatCount(value);
}
function dashDelta(metric) {
  if (!metric) return { text: '—', flat: true, good: false, up: false };
  const change = metric.percentageChange;
  const goodDir = metric.goodDirection || 'up';
  // No previous baseline but we do have activity this period -> it's brand new.
  if (change === null || change === undefined) {
    if (Number(metric.value || 0) > 0 && Number(metric.previousValue || 0) === 0) {
      return { text: 'New', flat: false, good: true, up: true, isNew: true };
    }
    return { text: '—', flat: true, good: false, up: false };
  }
  const rounded = Math.round(change);
  if (rounded === 0) return { text: 'No change', flat: false, good: false, up: false, neutral: true };
  const up = rounded > 0;
  // "Good" depends on the metric: for reply time, going down is good.
  const good = goodDir === 'down' ? !up : up;
  return { text: `${up ? '+' : ''}${rounded}% vs last week`, flat: false, good, up };
}
function dashDayLetter(dateStr) {
  const parts = String(dateStr || '').split('-');
  if (parts.length !== 3) return '';
  const d = new Date(Date.UTC(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])));
  return ['S', 'M', 'T', 'W', 'T', 'F', 'S'][d.getUTCDay()] || '';
}

// "2026-07-28" -> "Mon, Jul 28" for the chart hover tooltip.
function dashChartDate(dateStr) {
  const parts = String(dateStr || '').split('-');
  if (parts.length !== 3) return '';
  const d = new Date(Date.UTC(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])));
  const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return `${days[d.getUTCDay()]}, ${months[d.getUTCMonth()]} ${d.getUTCDate()}`;
}

// Relative "time ago" for the recent-leads list ("just now", "3h ago", "Jul 28").
function dashTimeAgo(value) {
  if (!value) return '';
  const then = new Date(String(value).replace(' ', 'T') + (String(value).includes('Z') ? '' : 'Z')).getTime();
  if (!Number.isFinite(then)) return '';
  const diff = Date.now() - then;
  if (diff < 0) return 'just now';
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'just now';
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `${days}d ago`;
  const d = new Date(then);
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return `${months[d.getUTCMonth()]} ${d.getUTCDate()}`;
}

// Two-letter avatar initials from a name (falls back to a person glyph).
function dashInitials(name) {
  const parts = String(name || '').trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return '·';
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

// Percentage change for an insight that carries current/previous evidence
// (used for the green "trending" pill). Returns null when not computable.
function dashInsightPct(ins) {
  const ev = (ins && ins.evidence) || {};
  const cur = Number(ev.current);
  const prev = Number(ev.previous);
  if (!Number.isFinite(cur) || !Number.isFinite(prev) || prev === 0) return null;
  return Math.round(((cur - prev) / Math.abs(prev)) * 100);
}

function Dashboard() {
  const [tourOpen, setTourOpen] = useStateApp(false);
  const [data, setData] = useStateApp(null);
  const [loading, setLoading] = useStateApp(true);
  const [error, setError] = useStateApp('');
  const [workspaceId, setWorkspaceId] = useStateApp(() => getStoredWorkspaceId());
  const [hoverBar, setHoverBar] = useStateApp(null);
  const [leads, setLeads] = useStateApp([]);

  useEffectApp(() => {
    try {
      if (!window.localStorage.getItem(getAppTourStorageKey())) {
        setTourOpen(true);
      }
    } catch (error) {
      setTourOpen(false);
    }
  }, []);

  // Keep the dashboard in sync with the workspace switcher.
  useEffectApp(() => {
    const onChange = event => setWorkspaceId(event.detail?.workspaceId || getStoredWorkspaceId());
    window.addEventListener('pluginchatbot:workspace-changed', onChange);
    return () => window.removeEventListener('pluginchatbot:workspace-changed', onChange);
  }, []);

  // Live analytics for the last 7 days (real data from /api/analytics/summary).
  useEffectApp(() => {
    let active = true;
    setLoading(true);
    setError('');

    const params = new URLSearchParams({ preset: 'last_7_days' });
    if (workspaceId) params.set('workspaceId', workspaceId);
    try { params.set('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'); } catch (tzError) {}

    fetch(`/api/analytics/summary?${params.toString()}`, {
      credentials: 'include',
      cache: 'no-store',
      headers: { 'cache-control': 'no-cache' },
    })
      .then(response => response.json().catch(() => ({})))
      .then(payload => {
        if (!active) return;
        if (!payload || !payload.ok) throw new Error(payload?.error || 'Unable to load dashboard data.');
        setData(payload);
      })
      .catch(loadError => { if (active) setError(loadError.message || 'Unable to load dashboard data.'); })
      .finally(() => { if (active) setLoading(false); });

    return () => { active = false; };
  }, [workspaceId]);

  // Most recent captured leads for the dashboard side panel.
  useEffectApp(() => {
    let active = true;
    const params = new URLSearchParams();
    if (workspaceId) params.set('workspaceId', workspaceId);

    fetch(`/api/leads?${params.toString()}`, {
      credentials: 'include',
      cache: 'no-store',
      headers: { 'cache-control': 'no-cache' },
    })
      .then(response => response.json().catch(() => ({})))
      .then(payload => {
        if (!active) return;
        const rows = Array.isArray(payload?.leads) ? payload.leads : [];
        rows.sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')));
        setLeads(rows.slice(0, 5));
      })
      .catch(() => { if (active) setLeads([]); });

    return () => { active = false; };
  }, [workspaceId]);

  const finishTour = () => {
    try {
      window.localStorage.setItem(getAppTourStorageKey(), 'complete');
    } catch (error) {
      // Local storage may be unavailable in private browsing.
    }
    setTourOpen(false);
  };

  const exportData = () => {
    const params = new URLSearchParams({ preset: 'last_7_days', dataset: 'summary' });
    if (workspaceId) params.set('workspaceId', workspaceId);
    window.location.assign(`/api/analytics/export?${params.toString()}`);
  };

  const metrics = data?.metrics || {};
  const cards = [
    { label: 'Conversations', metric: metrics.conversations },
    { label: 'Leads captured', metric: metrics.leads },
    { label: 'Avg. reply', metric: metrics.firstResponseMs },
    { label: 'Resolved', metric: metrics.aiContainmentRate },
  ];

  const points = Array.isArray(data?.timeseries) ? data.timeseries : [];
  const bars = points.map(point => ({ letter: dashDayLetter(point.date), value: Number(point.conversations || 0), label: dashChartDate(point.date) }));
  const maxBar = Math.max(1, ...bars.map(bar => bar.value));

  const topQuestions = (data?.questions?.top || []).slice(0, 5);

  const insights = (Array.isArray(data?.insights) ? data.insights : []).slice(0, 3);

  // Conversion funnel: only steps we actually have data for (widget impression
  // steps stay hidden until the analytics embed has been recording long enough).
  const funnelSteps = (Array.isArray(data?.funnel) ? data.funnel : []).filter(
    step => step && step.available !== false,
  );
  const funnelTop = funnelSteps.length ? Math.max(1, Number(funnelSteps[0].value || 0)) : 1;

  return (
    <div className="view">
      <div className="view-head">
        <div>
          <h1>Dashboard</h1>
          <div className="sub">Last 7 days · all channels</div>
        </div>
        <div className="view-actions" style={{display:'flex', gap:10}}>
          <button className="btn btn-secondary" type="button" onClick={() => setTourOpen(true)}>
            <Icon name="map" size={13}/>Product tour
          </button>
          <button className="btn btn-secondary" type="button"><Icon name="clock" size={13}/>Last 7 days</button>
          <button className="btn btn-primary" type="button" onClick={exportData}>Export</button>
        </div>
      </div>

      {error && (
        <div className="card" style={{borderColor:'#fda29b', background:'rgba(217,47,36,.06)', color:'#D92F24', marginBottom:14}}>
          {error}
        </div>
      )}

      <div className="kpi-grid">
        {cards.map(({ label, metric }) => {
          const delta = dashDelta(metric);
          const deltaColor = delta.flat || delta.neutral
            ? 'var(--pc-text-dim)'
            : delta.good ? '#16a34a' : '#D92F24';
          return (
            <div key={label} className="card">
              <div className="kpi-label">{label}</div>
              <div className="kpi-value">{loading ? '…' : dashFormatMetric(metric)}</div>
              <div className="kpi-delta" style={{display:'flex', alignItems:'center', gap:5, color:deltaColor, fontWeight:500}}>
                {loading || delta.flat ? (
                  <span style={{color:'var(--pc-text-dim)'}}>—</span>
                ) : delta.isNew ? (
                  <span style={{fontSize:11, fontWeight:600, padding:'1px 7px', borderRadius:999, background:'rgba(22,163,74,.12)', color:'#16a34a'}}>New</span>
                ) : (
                  <>
                    {!delta.neutral && <span style={{fontSize:11, lineHeight:1}}>{delta.up ? '▲' : '▼'}</span>}
                    <span>{delta.text}</span>
                  </>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {!loading && insights.length > 0 && (
        <div style={{display:'grid', gridTemplateColumns:`repeat(${Math.min(insights.length, 2)}, minmax(0,1fr))`, gap:16, marginTop:16}}>
          {insights.slice(0, 2).map((ins, i) => {
            const positive = ins.tone === 'positive';
            const negative = ins.tone === 'negative';
            const isAi = !positive && !negative; // neutral insights render as the AI card
            // Single brand-red palette across every insight card for consistency;
            // the icon + label still distinguish trending / attention / AI insight.
            const meta = positive
              ? { icon:'trendUp', eyebrow:'TRENDING UP' }
              : negative
              ? { icon:'alertTriangle', eyebrow:'NEEDS ATTENTION' }
              : { icon:'sparkles', eyebrow:'AI INSIGHT' };
            const theme = {
              accent:'#D92F24',
              tint:'rgba(217,47,36,.10)',
              grad:'linear-gradient(135deg, rgba(217,47,36,.08), #FFFFFF 55%)',
              ...meta,
            };
            const pct = dashInsightPct(ins);
            const ev = ins.evidence || {};
            const subtitle = isAi && ev.question
              ? <span>&ldquo;{ev.question}&rdquo;<span style={{color:'var(--pc-text-dim)', margin:'0 8px'}}>•</span>Asked {ev.total} times</span>
              : ins.detail;
            return (
              <div
                key={ins.id || i}
                className="dash-insight-card"
                style={{position:'relative', display:'flex', alignItems:'center', gap:18, padding:'22px 24px', background:theme.grad, border:'1px solid #ECECEC', borderLeft:`4px solid ${theme.accent}`, borderRadius:18, boxShadow:'0 1px 2px rgba(17,17,17,.04)'}}
              >
                <span style={{flex:'0 0 48px', width:48, height:48, borderRadius:'50%', background:theme.tint, color:theme.accent, display:'flex', alignItems:'center', justifyContent:'center'}}>
                  <Icon name={theme.icon} size={22}/>
                </span>
                <div style={{minWidth:0, flex:1}}>
                  <div style={{fontSize:11, fontWeight:700, letterSpacing:'.6px', color:theme.accent, marginBottom:6}}>{theme.eyebrow}</div>
                  <div style={{fontSize:17, fontWeight:700, color:'#111111', lineHeight:1.25, marginBottom:6}}>{ins.title}</div>
                  <div style={{fontSize:13, color:'var(--pc-text-muted)', lineHeight:1.45, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{subtitle}</div>
                </div>
                {isAi ? (
                  <button
                    type="button"
                    className="dash-insight-btn"
                    onClick={() => { if (window.location.pathname !== '/analytics') window.history.pushState({}, '', '/analytics'); window.dispatchEvent(new PopStateEvent('popstate')); }}
                    style={{flex:'0 0 auto', display:'flex', alignItems:'center', gap:6, fontSize:13, fontWeight:600, color:'#111111', background:'#F5F5F5', border:'1px solid #ECECEC', borderRadius:10, padding:'9px 14px', cursor:'pointer', whiteSpace:'nowrap'}}
                  >
                    View details <Icon name="arrowRight" size={14}/>
                  </button>
                ) : pct !== null ? (
                  <span style={{flex:'0 0 auto', display:'flex', alignItems:'center', gap:5, fontSize:14, fontWeight:700, color:theme.accent, background:theme.tint, borderRadius:999, padding:'7px 13px', whiteSpace:'nowrap'}}>
                    <Icon name={theme.icon} size={14}/>{pct > 0 ? '+' : ''}{pct}%
                  </span>
                ) : null}
              </div>
            );
          })}
        </div>
      )}

      <div className="dashboard-grid" style={{display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:14, marginTop:14}}>
        <div className="card">
          <div style={{display:'flex', justifyContent:'space-between', marginBottom:14}}>
            <div style={{fontSize:14, fontWeight:600}}>Conversations</div>
            <div style={{fontSize:12, color:'var(--pc-text-muted)'}}>Last 7 days</div>
          </div>
          {loading ? (
            <div style={{height:160, display:'flex', alignItems:'center', justifyContent:'center', color:'var(--pc-text-dim)', fontSize:13}}>Loading…</div>
          ) : bars.length === 0 || maxBar === 1 && bars.every(b => b.value === 0) ? (
            <div style={{height:160, display:'flex', alignItems:'center', justifyContent:'center', color:'var(--pc-text-dim)', fontSize:13}}>No conversations yet in this period.</div>
          ) : (
            <div style={{display:'flex', alignItems:'flex-end', gap:10, height:160}}>
              {bars.map((bar, i) => (
                <div
                  key={i}
                  style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:6}}
                  onMouseEnter={() => setHoverBar(i)}
                  onMouseLeave={() => setHoverBar(prev => (prev === i ? null : prev))}
                >
                  {/* Definite-height track so the bar's % height has a fixed reference (flex-end columns aren't stretched). */}
                  <div style={{position:'relative', width:'100%', height:130, display:'flex', alignItems:'flex-end'}}>
                    {hoverBar === i && (
                      <div
                        style={{position:'absolute', bottom:'calc(100% + 8px)', left:'50%', transform:'translateX(-50%)', background:'#111111', color:'#fff', borderRadius:8, padding:'8px 10px', boxShadow:'0 6px 20px rgba(0,0,0,.22)', whiteSpace:'nowrap', pointerEvents:'none', zIndex:5, textAlign:'center'}}
                      >
                        <div style={{fontSize:11, color:'rgba(255,255,255,.7)', marginBottom:2}}>{bar.label}</div>
                        <div style={{fontSize:13, fontWeight:600}}>{bar.value} conversation{bar.value === 1 ? '' : 's'}</div>
                        <div style={{position:'absolute', top:'100%', left:'50%', transform:'translateX(-50%)', width:0, height:0, borderLeft:'6px solid transparent', borderRight:'6px solid transparent', borderTop:'6px solid #111111'}}/>
                      </div>
                    )}
                    <div style={{width:'100%', height:`${Math.max(4, (bar.value / maxBar) * 100)}%`, background:'linear-gradient(180deg,#D92F24,#111111)', borderRadius:6, opacity:hoverBar === i ? 1 : 0.55 + (bar.value / maxBar) * 0.45, cursor:'pointer', transition:'opacity .12s ease'}}/>
                  </div>
                  <div style={{fontSize:11, color: hoverBar === i ? '#D92F24' : 'var(--pc-text-dim)', fontWeight: hoverBar === i ? 600 : 400}}>{bar.letter}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="card">
          <div style={{fontSize:14, fontWeight:600, marginBottom:14}}>Top questions</div>
          {loading ? (
            <div style={{padding:'10px 0', color:'var(--pc-text-dim)', fontSize:13}}>Loading…</div>
          ) : topQuestions.length === 0 ? (
            <div style={{padding:'10px 0', color:'var(--pc-text-dim)', fontSize:13}}>No questions asked yet.</div>
          ) : (
            topQuestions.map(row => (
              <div key={row.question} style={{padding:'10px 0', borderBottom:'1px solid var(--pc-border)', display:'flex', justifyContent:'space-between', alignItems:'center', gap:12}}>
                <span style={{fontSize:13, color:'var(--pc-text)', textTransform:'capitalize'}}>{row.question}</span>
                <span style={{fontSize:12, color:'var(--pc-text-muted)', fontFamily:'var(--pc-font-mono)'}}>{row.total}</span>
              </div>
            ))
          )}
        </div>
      </div>

      <div className="dashboard-grid" style={{display:'grid', gridTemplateColumns:'1fr 1.4fr', gap:14, marginTop:14}}>
        <div className="card">
          <div style={{display:'flex', justifyContent:'space-between', marginBottom:14}}>
            <div style={{fontSize:14, fontWeight:600}}>Conversion funnel</div>
            <div style={{fontSize:12, color:'var(--pc-text-muted)'}}>Last 7 days</div>
          </div>
          {loading ? (
            <div style={{padding:'10px 0', color:'var(--pc-text-dim)', fontSize:13}}>Loading…</div>
          ) : funnelSteps.length === 0 ? (
            <div style={{padding:'10px 0', color:'var(--pc-text-dim)', fontSize:13}}>No funnel data yet.</div>
          ) : (
            <div style={{display:'flex', flexDirection:'column', gap:12}}>
              {funnelSteps.map((step, i) => {
                const value = Number(step.value || 0);
                const width = Math.max(6, (value / funnelTop) * 100);
                const rate = i === 0 ? 100 : Math.round((value / funnelTop) * 100);
                return (
                  <div key={step.key || i}>
                    <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:5}}>
                      <span style={{fontSize:12.5, color:'var(--pc-text)'}}>{step.label}</span>
                      <span style={{display:'flex', alignItems:'center', gap:8}}>
                        <b style={{fontSize:12.5, color:'var(--pc-text)', fontFamily:'var(--pc-font-mono)'}}>{value}</b>
                        <span style={{fontSize:12.5, fontWeight:700, color:'#D92F24', background:'rgba(217,47,36,.10)', borderRadius:999, padding:'2px 9px', minWidth:44, textAlign:'center'}}>{rate}%</span>
                      </span>
                    </div>
                    <div style={{height:10, borderRadius:6, background:'var(--pc-border)', overflow:'hidden'}}>
                      <div style={{width:`${width}%`, height:'100%', borderRadius:6, background:'linear-gradient(90deg,#D92F24,#111111)'}}/>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <div className="card">
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
            <div style={{fontSize:14, fontWeight:600}}>Recent leads</div>
            <a href="/leads" onClick={e => { e.preventDefault(); if (window.location.pathname !== '/leads') window.history.pushState({}, '', '/leads'); window.dispatchEvent(new PopStateEvent('popstate')); }} style={{fontSize:12, color:'#D92F24', textDecoration:'none', fontWeight:500}}>View all</a>
          </div>
          {leads.length === 0 ? (
            <div style={{padding:'10px 0', color:'var(--pc-text-dim)', fontSize:13}}>No leads captured yet.</div>
          ) : (
            <div>
              {leads.map(lead => (
                <div key={lead.id} style={{padding:'9px 0', borderBottom:'1px solid var(--pc-border)', display:'flex', alignItems:'center', gap:11}}>
                  <span style={{flex:'0 0 34px', width:34, height:34, borderRadius:'50%', background:'linear-gradient(135deg,#D92F24,#7a1a14)', color:'#fff', fontSize:12, fontWeight:600, display:'flex', alignItems:'center', justifyContent:'center'}}>{dashInitials(lead.name)}</span>
                  <div style={{minWidth:0, flex:1}}>
                    <div style={{fontSize:13, fontWeight:600, color:'var(--pc-text)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{lead.name || 'Anonymous visitor'}</div>
                    <div style={{fontSize:12, color:'var(--pc-text-muted)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{lead.email || lead.phone || '—'}</div>
                  </div>
                  <span style={{fontSize:11, color:'var(--pc-text-dim)', whiteSpace:'nowrap'}}>{dashTimeAgo(lead.createdAt)}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {tourOpen && <AppTour onClose={finishTour}/>}
    </div>
  );
}

function AppTour({ onClose }) {
  const steps = [
    { target: 'dashboard', title: 'Start from Dashboard', description: 'Review activity and use this page as the starting point for your chatbot setup.' },
    { target: 'aiBuilder', title: 'Open AI Builder', description: 'Choose widget styling, chatbot settings, Knowledge Base, website access, and install options from one page.' },
    { target: 'integrations', title: 'Connect Integrations', description: 'Open an integration card to configure live chat, WhatsApp, or HubSpot in a focused window.' },
    { target: 'templates', title: 'Edit Saved Templates', description: 'Reopen saved chatbot templates later to update the same embed code.' },
  ];
  const [stepIndex, setStepIndex] = useStateApp(0);
  const step = steps[stepIndex];

  useEffectApp(() => {
    document.documentElement.classList.add('has-app-tour');
    return () => document.documentElement.classList.remove('has-app-tour');
  }, []);

  useEffectApp(() => {
    const target = document.querySelector(`[data-tour="${step.target}"]`);
    if (!target) return undefined;

    target.classList.add('is-tour-target');
    target.scrollIntoView({ block: 'nearest' });

    return () => target.classList.remove('is-tour-target');
  }, [step.target]);

  useEffectApp(() => {
    const handleKeyDown = event => {
      if (event.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  return (
    <div className="app-tour-backdrop" role="presentation">
      <section className="app-tour-dialog" role="dialog" aria-modal="true" aria-labelledby="app-tour-title">
        <div className="app-tour-progress">
          <span>Setup guide</span>
          <strong>{stepIndex + 1} / {steps.length}</strong>
        </div>
        <div className="app-tour-icon"><Icon name="map" size={24}/></div>
        <h2 id="app-tour-title">{step.title}</h2>
        <p>{step.description}</p>
        <div className="app-tour-dots" aria-hidden="true">
          {steps.map((item, index) => <span key={item.target} className={index === stepIndex ? 'is-active' : ''}/>) }
        </div>
        <div className="app-tour-actions">
          <button className="btn btn-secondary" type="button" onClick={onClose}>Skip tour</button>
          <div>
            {stepIndex > 0 && (
              <button className="btn btn-secondary" type="button" onClick={() => setStepIndex(index => index - 1)}>Back</button>
            )}
            <button
              className="btn btn-primary"
              type="button"
              onClick={() => stepIndex === steps.length - 1 ? onClose() : setStepIndex(index => index + 1)}
            >
              {stepIndex === steps.length - 1 ? 'Finish' : 'Next'}
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

function getAppTourStorageKey() {
  const user = window.PluginChatBotCurrentUser || {};
  const identity = user.userId || user.email || 'current-user';
  return `pluginchatbot_app_tour_${identity}`;
}

function Conversations() {
  const list = [
    {id:1, name:'Sarah M.', last:'Yes, please call me back today', time:'2m', unread:true, lead:true},
    {id:2, name:'Visitor', last:'How much for a hot water repair?', time:'14m', unread:true},
    {id:3, name:'Liam C.', last:'Thanks — booked for Thursday', time:'1h'},
    {id:4, name:'Visitor', last:'Do you service Brunswick?', time:'2h'},
    {id:5, name:'Priya K.', last:'Sent the quote across, cheers', time:'5h'},
  ];
  const [sel, setSel] = useStateApp(1);
  const c = list.find(x=>x.id===sel);
  return (
    <div className="view conversation-view" style={{padding:0, height:'calc(100vh - 64px)', display:'grid', gridTemplateColumns:'320px 1fr 280px'}}>
      <div className="conversation-list" style={{borderRight:'1px solid var(--pc-border)', overflowY:'auto'}}>
        <div style={{padding:'18px 20px', borderBottom:'1px solid var(--pc-border)'}}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:8}}>Inbox</div>
          <div style={{display:'flex', gap:6}}>
            <span className="pill" style={{background:'rgba(217,47,36,0.07)', color:'#D92F24', border:'1px solid rgba(217,47,36,0.26)'}}>All · 12</span>
            <span className="pill dim">Unread · 4</span>
            <span className="pill dim">Leads · 7</span>
          </div>
        </div>
        {list.map(c=>(
          <button key={c.id} onClick={()=>setSel(c.id)} style={{
            width:'100%', textAlign:'left', padding:'14px 20px', background: sel===c.id?'rgba(217,47,36,0.06)':'transparent',
            borderLeft: sel===c.id?'2px solid #D92F24':'2px solid transparent',
            borderBottom:'1px solid var(--pc-border)', cursor:'pointer'
          }}>
            <div style={{display:'flex', justifyContent:'space-between', marginBottom:4}}>
              <span style={{fontSize:13, fontWeight:600}}>{c.name}</span>
              <span style={{fontSize:11, color:'var(--pc-text-muted)'}}>{c.time}</span>
            </div>
            <div style={{fontSize:12.5, color:'var(--pc-text-muted)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{c.last}</div>
            <div style={{display:'flex', gap:5, marginTop:6}}>
              {c.unread && <span className="pill" style={{background:'rgba(217,47,36,0.07)', color:'#D92F24', border:'1px solid rgba(217,47,36,0.26)'}}>New</span>}
              {c.lead && <span className="pill success">Lead</span>}
            </div>
          </button>
        ))}
      </div>

      <div className="conversation-chat" style={{display:'flex', flexDirection:'column'}}>
        <div className="conversation-chat-head" style={{padding:'14px 22px', borderBottom:'1px solid var(--pc-border)', display:'flex', alignItems:'center', gap:12}}>
          <div className="tb-avatar">{c.name[0]}</div>
          <div style={{flex:1}}>
            <div style={{fontSize:14, fontWeight:600}}>{c.name}</div>
            <div style={{fontSize:12, color:'var(--pc-text-muted)'}}>via Website widget · acmeplumbing.com</div>
          </div>
          <button className="btn btn-secondary"><Icon name="contact" size={13}/>Hand off</button>
        </div>
        <div style={{flex:1, padding:'24px 28px', overflowY:'auto', display:'flex', flexDirection:'column', gap:12}}>
          <Bubble role="user">Do you offer emergency plumbing?</Bubble>
          <Bubble role="bot">Yes. We offer 24/7 emergency plumbing. Would you like to request a callback?</Bubble>
          <Bubble role="user">Yes please, today if possible</Bubble>
          <Bubble role="bot">Got it. Could I grab your name and best contact number?</Bubble>
          <Bubble role="user">Sarah M., 0412 555 219</Bubble>
          <Bubble role="bot">Thanks Sarah — a plumber will call you within 15 minutes.</Bubble>
          <div style={{padding:12, background:'rgba(217,47,36,0.06)', border:'1px solid rgba(217,47,36,0.24)', borderRadius:10, fontSize:12.5, color:'#D92F24', display:'flex', alignItems:'center', gap:8}}>
            <Icon name="checkCircle" size={14}/> Lead captured · saved to Leads · pushed to email
          </div>
        </div>
        <div style={{padding:14, borderTop:'1px solid var(--pc-border)', display:'flex', gap:10, alignItems:'center'}}>
          <input placeholder="Reply as a human…" style={{flex:1, padding:'11px 14px', background:'var(--pc-bg-card)', border:'1px solid var(--pc-border)', borderRadius:10, color:'var(--pc-text)', fontFamily:'inherit', fontSize:13}}/>
          <button className="btn btn-primary"><Icon name="send" size={13}/>Send</button>
        </div>
      </div>

      <div className="visitor-panel" style={{borderLeft:'1px solid var(--pc-border)', padding:22, overflowY:'auto'}}>
        <div style={{fontSize:12, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--pc-text-muted)', marginBottom:12}}>Visitor</div>
        <div style={{fontSize:15, fontWeight:600, marginBottom:4}}>{c.name}</div>
        <div style={{fontSize:13, color:'var(--pc-text-muted)', marginBottom:18}}>0412 555 219 · sarah@example.com</div>
        <DashboardField label="Page" v="/services/emergency"/>
        <DashboardField label="Source" v="Google · organic"/>
        <DashboardField label="First seen" v="3 mins ago"/>
        <DashboardField label="Status" v={<span className="pill success">Qualified lead</span>}/>
      </div>
    </div>
  );
}

function Bubble({role, children}) {
  const isUser = role==='user';
  return (
    <div style={{
      maxWidth:'72%',
      alignSelf: isUser?'flex-end':'flex-start',
      padding:'10px 14px', borderRadius:14, fontSize:13.5, lineHeight:1.5,
      background: isUser?'#D92F24':'#111111',
      color: isUser?'#fff':'var(--pc-text)',
      border: isUser?'none':'1px solid var(--pc-border)',
      borderBottomRightRadius: isUser?4:14,
      borderBottomLeftRadius: isUser?14:4,
    }}>{children}</div>
  );
}
function DashboardField({label, v}) {
  return <div style={{padding:'10px 0', borderBottom:'1px solid var(--pc-border)'}}>
    <div style={{fontSize:11, color:'var(--pc-text-dim)', textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:4}}>{label}</div>
    <div style={{fontSize:13}}>{v}</div>
  </div>;
}

window.Dashboard = Dashboard;
window.Conversations = Conversations;
