/* global React, Icon */
const { useState, useEffect } = React;

function Analytics({ goto }) {
  const [days, setDays] = useState(7);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [ga4, setGa4] = useState(null);

  useEffect(() => {
    fetch(`/api/analytics/overview?days=${days}`, { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then(setData)
      .catch((e) => setError(String(e)));
    fetch(`/api/analytics/ga4?days=${days}`, { credentials: 'include' })
      .then((r) => r.ok ? r.json() : { connected: false, reason: r.statusText })
      .then(setGa4)
      .catch(() => setGa4({ connected: false, reason: 'fetch failed' }));
  }, [days]);

  if (error) {
    return <div style={{ padding: 60, color: 'var(--red)' }}>Failed to load: {error}</div>;
  }
  if (!data) {
    return <div style={{ padding: 60, color: 'var(--text-dim)' }}>Loading…</div>;
  }

  const k = data.kpi;
  const m = data.messaging;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Insights</div>
          <h1 className="page-title">Analytics</h1>
        </div>
        <div className="page-header-right" style={{ display: 'flex', gap: 8 }}>
          {[
            { v: 7, l: '7d' },
            { v: 14, l: '14d' },
            { v: 30, l: '30d' },
            { v: 90, l: '90d' },
          ].map((o) => (
            <button
              key={o.v}
              className="btn btn-sm"
              style={{
                background: days === o.v ? 'var(--accent-bg)' : 'transparent',
                borderColor: days === o.v ? 'var(--accent)' : 'var(--divider)',
                color: days === o.v ? 'var(--accent)' : 'var(--text-secondary)',
              }}
              onClick={() => setDays(o.v)}
            >
              {o.l}
            </button>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: 28 }}>
        {/* Top KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
          <Kpi label="Open deals" value={k.open_deals_count} sub={`AED ${fmt(k.open_deals_value_aed)} pipeline`} />
          <Kpi label="Closed (30d)" value={`AED ${fmt(k.closed_won_30d_aed)}`} sub={`${k.closed_won_30d_count} deal${k.closed_won_30d_count === 1 ? '' : 's'}`} />
          <Kpi label="Paid (30d)" value={`AED ${fmt(k.paid_30d_aed)}`} sub={`Outstanding: AED ${fmt(k.outstanding_aed)}`} />
          <Kpi label={`New contacts (${days}d)`} value={k.new_contacts_week} sub={`${k.contacts_total} total`} accent />
        </div>

        {/* Bookings + replies row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
          <Kpi label="Calls held" value={k.bookings_week} sub={`${k.no_shows_week} no-show${k.no_shows_week === 1 ? '' : 's'}`} />
          <Kpi label="Calls upcoming" value={k.bookings_upcoming} />
          <Kpi label="Replies received" value={k.replies_week} sub="distinct contacts" />
          <Kpi label="Reply rate" value={k.new_contacts_week > 0 ? `${Math.round((k.replies_week / k.new_contacts_week) * 100)}%` : '—'} sub={`replies / new contacts`} />
        </div>

        {/* Messaging panel */}
        <h3 className="section-title" style={{ margin: '0 0 12px' }}>Messaging volume</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
          <ChannelCard label="LinkedIn" data={m.linkedin} dot="#0a66c2" />
          <ChannelCard label="WhatsApp" data={m.whatsapp} dot="#25d366" />
          <ChannelCard label="Email" data={m.email} dot="#a3a3a3" />
          <ChannelCard label="Instagram" data={m.instagram} dot="#e4405f" />
        </div>

        {/* Email engagement */}
        <h3 className="section-title" style={{ margin: '0 0 12px' }}>Email engagement</h3>
        <div className="card" style={{ padding: 18, marginBottom: 22 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            <Stat label="Sent" value={m.email_engagement.sent} mono />
            <Stat label="Open rate" value={`${m.email_engagement.open_rate}%`} mono accent />
            <Stat label="Click rate" value={`${m.email_engagement.click_rate}%`} mono accent />
            <Stat label="Delivered rate" value={`${m.email_engagement.delivered_rate}%`} mono />
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 14 }}>
            Tracking via Resend webhook (open/click pixel + link rewrite). Gmail-direct sends are tracked as sent only — Google doesn't expose opens.
          </div>
        </div>

        {/* Pipeline distribution */}
        <h3 className="section-title" style={{ margin: '0 0 12px' }}>Pipeline distribution</h3>
        <div className="card" style={{ padding: 18, marginBottom: 22 }}>
          <PipelineBars stages={data.pipeline_stages} />
        </div>

        {/* GA4 — lineagroup.ae website */}
        <h3 className="section-title" style={{ margin: '0 0 12px' }}>Website · lineagroup.ae (GA4)</h3>
        {!ga4 && <div style={{ color: 'var(--text-dim)', fontSize: 12, marginBottom: 22 }}>Loading GA4…</div>}
        {ga4 && !ga4.connected && (
          <div className="card" style={{ padding: 18, marginBottom: 22 }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>Not connected</div>
            <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 10 }}>{ga4.reason}</div>
            {ga4.needs_reauth && (
              <a href="/auth/google/connect" className="btn btn-sm btn-primary">Re-authorize Google to grant Analytics scope</a>
            )}
          </div>
        )}
        {ga4 && ga4.connected && <Ga4Panel ga4={ga4} />}

        {/* Plug-in placeholders */}
        <h3 className="section-title" style={{ margin: '0 0 12px' }}>External integrations</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          <PlaceholderCard
            title="Meta Ads"
            status="Connected"
            note="6 client accounts (G&G Dolci, Undrgoods, Stride, EnduraXcel, Dolce Salato, Monviso). Live spend + ROAS pulled per account."
            cta="View Meta Ads"
          />
          <PlaceholderCard
            title="LinkedIn Ads"
            status="Pending OAuth + MDP approval"
            note="Read-only campaign analytics once your developer.linkedin.com app is set up + Marketing Developer Platform is granted."
            cta={null}
          />
          <PlaceholderCard
            title="Stripe"
            status="Connected"
            note={`AED ${fmt(k.paid_30d_aed)} collected (30d), AED ${fmt(k.outstanding_aed)} outstanding`}
            cta={null}
          />
        </div>

        <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 24 }}>
          Window: last {days} days · Generated {new Date(data.generated_at).toLocaleString()}
        </div>
      </div>
    </div>
  );
}

function fmt(n) {
  if (n == null) return '0';
  if (window.fmtAED) return window.fmtAED(n);
  return Math.round(n).toLocaleString();
}

function Kpi({ label, value, sub, accent }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div className="label" style={{ marginBottom: 8 }}>{label}</div>
      <div className="mono" style={{ fontSize: 28, fontWeight: 900, color: accent ? 'var(--accent)' : 'var(--text)', letterSpacing: '-0.02em' }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function Stat({ label, value, mono, accent }) {
  return (
    <div>
      <div className="label" style={{ marginBottom: 6 }}>{label}</div>
      <div className={mono ? 'mono' : ''} style={{ fontSize: 22, fontWeight: 800, color: accent ? 'var(--accent)' : 'var(--text)' }}>{value}</div>
    </div>
  );
}

function ChannelCard({ label, data, dot }) {
  return (
    <div className="card" style={{ padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <div style={{ width: 8, height: 8, borderRadius: '50%', background: dot }}></div>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{label}</div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
        <span style={{ color: 'var(--text-dim)' }}>Sent</span>
        <span className="mono" style={{ color: 'var(--accent)' }}>{data.sent_today}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
        <span style={{ color: 'var(--text-dim)' }}>Received</span>
        <span className="mono">{data.received_today}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--divider)' }}>
        <span style={{ color: 'var(--text-dim)' }}>All-time</span>
        <span className="mono" style={{ color: 'var(--text-dim)' }}>{data.sent_total} / {data.received_total}</span>
      </div>
    </div>
  );
}

function PipelineBars({ stages }) {
  const entries = Object.entries(stages || {});
  if (entries.length === 0) return <div style={{ color: 'var(--text-dim)', fontSize: 12 }}>No contacts yet.</div>;
  const max = Math.max(...entries.map(([, n]) => n));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {entries.map(([stage, n]) => (
        <div key={stage} style={{ display: 'grid', gridTemplateColumns: '180px 1fr 60px', alignItems: 'center', gap: 10, fontSize: 12 }}>
          <span>{stage}</span>
          <div style={{ background: 'var(--divider)', height: 6, position: 'relative' }}>
            <div style={{ background: 'var(--accent)', width: `${(n / max) * 100}%`, height: '100%' }}></div>
          </div>
          <span className="mono" style={{ color: 'var(--accent)', textAlign: 'right' }}>{n}</span>
        </div>
      ))}
    </div>
  );
}

function PlaceholderCard({ title, status, note, cta }) {
  const isConnected = status === 'Connected';
  return (
    <div className="card" style={{ padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>{title}</span>
        <span style={{
          marginLeft: 'auto',
          fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em',
          padding: '2px 8px', border: `1px solid ${isConnected ? 'rgba(34,197,94,0.5)' : 'var(--divider)'}`,
          color: isConnected ? 'var(--accent)' : 'var(--text-dim)',
          borderRadius: 3,
        }}>{status}</span>
      </div>
      <div style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.5, marginBottom: 12 }}>{note}</div>
      {cta && (
        <button className="btn btn-sm" disabled>{cta}</button>
      )}
    </div>
  );
}

function Ga4Panel({ ga4 }) {
  const k = ga4.kpi || {};
  const rt = ga4.realtime || {};
  return (
    <div style={{ marginBottom: 22 }}>
      <div className="card" style={{ padding: 18, marginBottom: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 10, height: 10, borderRadius: '50%', background: rt.active_users > 0 ? 'var(--accent)' : 'var(--text-dim)', boxShadow: rt.active_users > 0 ? '0 0 12px var(--accent)' : 'none' }}></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Active users right now</div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>Property {ga4.property_id} · last 30 min</div>
        </div>
        <div className="mono" style={{ fontSize: 28, fontWeight: 900, color: 'var(--accent)' }}>{rt.active_users || 0}</div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Kpi label="Users" value={k.users ?? 0} sub={`${k.new_users ?? 0} new`} />
        <Kpi label="Sessions" value={k.sessions ?? 0} />
        <Kpi label="Pageviews" value={k.pageviews ?? 0} />
        <Kpi label="Avg session" value={`${Math.floor((k.avg_session_duration_sec || 0) / 60)}:${String(Math.round((k.avg_session_duration_sec || 0) % 60)).padStart(2, '0')}`} sub={`${k.engagement_rate ?? 0}% engaged`} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="card" style={{ padding: 16 }}>
          <div className="label" style={{ marginBottom: 10 }}>Top pages</div>
          {(ga4.top_pages || []).length === 0 && <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>No data yet.</div>}
          {(ga4.top_pages || []).slice(0, 8).map((p, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px', gap: 6, fontSize: 11, padding: '6px 0', borderTop: i > 0 ? '1px solid var(--divider)' : 'none' }}>
              <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={p.title || p.path}>
                <span style={{ color: 'var(--text)' }}>{p.path || '/'}</span>
                {p.title && <span style={{ color: 'var(--text-dim)' }}> · {p.title}</span>}
              </div>
              <span className="mono" style={{ textAlign: 'right', color: 'var(--accent)' }}>{p.views}</span>
            </div>
          ))}
        </div>

        <div className="card" style={{ padding: 16 }}>
          <div className="label" style={{ marginBottom: 10 }}>Traffic sources</div>
          {(ga4.sources || []).length === 0 && <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>No data yet.</div>}
          {(ga4.sources || []).slice(0, 8).map((s, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px 60px', gap: 6, fontSize: 11, padding: '6px 0', borderTop: i > 0 ? '1px solid var(--divider)' : 'none' }}>
              <span>{s.channel}</span>
              <span className="mono" style={{ textAlign: 'right', color: 'var(--text-dim)' }}>{s.users}u</span>
              <span className="mono" style={{ textAlign: 'right', color: 'var(--accent)' }}>{s.sessions}s</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Analytics });
