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

/* ============================================================
   LINKEDIN CAMPAIGN — list + builder
   Connection campaigns: pick a lead list, set a daily cap,
   send N connection requests/day until the list is finished.
   ============================================================ */

const liTh = { padding: '10px 20px', textAlign: 'left', fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' };
const liTd = { padding: '12px 20px', verticalAlign: 'middle', color: 'var(--text-secondary)' };

function LinkedInCampaigns({ goto }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Outreach · LinkedIn</div>
          <h1 className="page-title">LinkedIn Campaign</h1>
          <div className="page-subtitle">{window.LINKEDIN_CAMPAIGNS.length} campaigns · {window.LINKEDIN_CAMPAIGNS.filter(c => c.status === 'active').length} active</div>
        </div>
        <div className="page-header-right">
          <button className="btn btn-primary" onClick={() => goto('linkedin-builder', 'li4')}>
            <Icon name="plus" size={12} /> New campaign
          </button>
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--divider)' }}>
              <th style={liTh}>Name</th>
              <th style={liTh}>Lead List</th>
              <th style={liTh}>Status</th>
              <th style={liTh}>Daily Cap</th>
              <th style={liTh}>Progress</th>
              <th style={liTh}>Accepted</th>
              <th style={liTh}>Replied</th>
              <th style={liTh}></th>
            </tr>
          </thead>
          <tbody>
            {window.LINKEDIN_CAMPAIGNS.map(c => {
              const list = window.LEAD_LISTS.find(l => l.id === c.listId);
              const total = list?.count || 0;
              const pct = total ? Math.round((c.sent / total) * 100) : 0;
              const acceptRate = c.sent ? ((c.accepted / c.sent) * 100).toFixed(1) : '0.0';
              const replyRate = c.accepted ? ((c.replied / c.accepted) * 100).toFixed(1) : '0.0';
              return (
                <tr key={c.id} onClick={() => goto('linkedin-builder', c.id)} style={{ borderBottom: '1px solid var(--divider)', cursor: 'pointer' }}>
                  <td style={liTd}>
                    <div style={{ fontWeight: 500, color: 'var(--text)' }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{c.account}</div>
                  </td>
                  <td style={liTd}>
                    <div style={{ color: 'var(--text)' }}>{list?.name || '—'}</div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{total} leads</div>
                  </td>
                  <td style={liTd}><StatusPill status={c.status} /></td>
                  <td style={{...liTd, fontFamily: 'var(--font-mono)' }}>{c.dailyCap}/day</td>
                  <td style={liTd}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 160 }}>
                      <div style={{ flex: 1, height: 4, background: 'var(--raised)', position: 'relative' }}>
                        <div style={{ position: 'absolute', inset: 0, width: pct + '%', background: c.status === 'completed' ? 'var(--green, #22c55e)' : 'var(--accent)' }}></div>
                      </div>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', minWidth: 60, textAlign: 'right' }}>{c.sent}/{total}</span>
                    </div>
                  </td>
                  <td style={{...liTd, fontFamily: 'var(--font-mono)', color: 'var(--accent)' }}>
                    {c.accepted} <span style={{ color: 'var(--text-dim)' }}>({acceptRate}%)</span>
                  </td>
                  <td style={{...liTd, fontFamily: 'var(--font-mono)' }}>
                    {c.replied} <span style={{ color: 'var(--text-dim)' }}>({replyRate}%)</span>
                  </td>
                  <td style={liTd}><Icon name="chevRight" size={13} style={{ color: 'var(--text-dim)' }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function LinkedInCampaignBuilder({ campaignId, goto }) {
  const c = window.LINKEDIN_CAMPAIGNS.find(x => x.id === campaignId) || window.LINKEDIN_CAMPAIGNS[0];
  const [listId, setListId] = useState(c.listId);
  const [cap, setCap] = useState(c.dailyCap);
  const [account, setAccount] = useState(c.account);
  const list = window.LEAD_LISTS.find(l => l.id === listId);
  const total = list?.count || 0;
  const pct = total ? Math.round((c.sent / total) * 100) : 0;
  const remaining = Math.max(0, total - c.sent);
  const eta = cap > 0 ? Math.ceil(remaining / cap) : 0;
  const acceptRate = c.sent ? ((c.accepted / c.sent) * 100).toFixed(1) : '0.0';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <button className="btn btn-ghost btn-sm" style={{ padding: '4px 6px', marginBottom: 6 }} onClick={() => goto('linkedin-campaigns')}>
            <Icon name="chevLeft" size={12} /> LinkedIn Campaign
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <h1 className="page-title" style={{ margin: 0 }}>{c.name}</h1>
            <StatusPill status={c.status} />
          </div>
        </div>
        <div className="page-header-right">
          {c.status === 'draft' && <button className="btn btn-primary"><Icon name="play" size={12} /> Start campaign</button>}
          {c.status === 'active' && <button className="btn"><Icon name="pause" size={12} /> Pause</button>}
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
        <div style={{ maxWidth: 880, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* LIVE PROGRESS — shown when active/completed */}
          {(c.status === 'active' || c.status === 'completed') && (
            <div className="card" style={{ padding: 20 }}>
              <div className="label" style={{ marginBottom: 14 }}>Progress</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 18 }}>
                <Stat label="Sent" value={c.sent} sub={`of ${total}`} />
                <Stat label="Accepted" value={c.accepted} sub={`${acceptRate}%`} accent />
                <Stat label="Replied" value={c.replied} sub={c.accepted ? `${((c.replied/c.accepted)*100).toFixed(1)}% of accepted` : '—'} />
                <Stat label="Days running" value={c.startedDays} sub={c.status === 'completed' ? 'completed' : `~${eta} days left`} />
              </div>
              <div style={{ height: 6, background: 'var(--raised)', position: 'relative' }}>
                <div style={{ position: 'absolute', inset: 0, width: pct + '%', background: c.status === 'completed' ? 'var(--green, #22c55e)' : 'var(--accent)' }}></div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: 'var(--text-dim)' }} className="mono">
                <span>{pct}% complete</span>
                <span>{remaining} remaining</span>
              </div>
            </div>
          )}

          {/* SETUP */}
          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={liStep}>1</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Lead List</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>Which list to send connection requests from</div>
              </div>
            </div>
            <div style={{ padding: 20 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {window.LEAD_LISTS.map(l => (
                  <label key={l.id} style={{
                    padding: 12, background: 'var(--surface)',
                    border: '1px solid', borderColor: listId === l.id ? 'var(--accent)' : 'var(--divider)',
                    display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
                  }}>
                    <input type="radio" name="ll" checked={listId === l.id} onChange={() => setListId(l.id)} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{l.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{l.source}</div>
                    </div>
                    <div className="mono" style={{ fontSize: 13, color: 'var(--accent)' }}>{l.count}</div>
                    <div style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>leads</div>
                  </label>
                ))}
              </div>
              <button className="btn btn-sm" style={{ marginTop: 10 }}><Icon name="plus" size={11} /> Import new list</button>
            </div>
          </div>

          {/* SENDING ACCOUNT */}
          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={liStep}>2</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Sending Account</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>Which connected LinkedIn account sends from</div>
              </div>
            </div>
            <div style={{ padding: 20 }}>
              <select className="input" value={account} onChange={(e) => setAccount(e.target.value)}>
                <option>Sebastiano · Linea</option>
                <option>Sebastiano · Personal</option>
                <option>Mira · Linea</option>
              </select>
            </div>
          </div>

          {/* DAILY CAP + INVITE NOTE */}
          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={liStep}>3</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Daily Send Cap</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>Connection requests per day until the list is finished</div>
              </div>
            </div>
            <div style={{ padding: 20 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 14 }}>
                <input
                  type="range" min="5" max="50" step="5"
                  value={cap} onChange={(e) => setCap(parseInt(e.target.value))}
                  style={{ flex: 1, accentColor: 'var(--accent)' }}
                />
                <div style={{ minWidth: 100, textAlign: 'right' }}>
                  <span className="mono" style={{ fontSize: 22, color: 'var(--accent)' }}>{cap}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 4 }}>/day</span>
                </div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-dim)' }} className="mono">
                <span>5 (safe)</span>
                <span>20 (recommended)</span>
                <span>50 (aggressive)</span>
              </div>
              <div style={{ marginTop: 16, padding: 12, background: 'var(--bg)', border: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="clock" size={14} style={{ color: 'var(--accent)' }} />
                <div style={{ fontSize: 12 }}>
                  Sending <span className="mono" style={{ color: 'var(--accent)' }}>{cap}</span> per day to <span className="mono" style={{ color: 'var(--accent)' }}>{total}</span> leads
                  {' · finishes in '}
                  <span className="mono" style={{ color: 'var(--accent)' }}>~{Math.ceil(total / cap)} days</span>
                </div>
              </div>
            </div>
          </div>

          {/* INVITE MESSAGE */}
          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={liStep}>4</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Invite Message</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>Optional · 200 char max · sent with the connection request</div>
              </div>
            </div>
            <div style={{ padding: 20 }}>
              <textarea
                className="textarea"
                style={{ minHeight: 90, fontSize: 13 }}
                maxLength={200}
                defaultValue="Hey {{first_name}} — saw your work at {{company}}. We help DTC brands in the region scale funnel + email ops. Would love to connect."
              />
              <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 6, fontFamily: 'var(--font-mono)' }}>
                {'{{first_name}}'} · {'{{company}}'} · {'{{title}}'}
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}

const liStep = {
  width: 28, height: 28,
  background: 'var(--accent-bg)', color: 'var(--accent)',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600,
};

function Stat({ label, value, sub, accent }) {
  return (
    <div>
      <div className="label" style={{ marginBottom: 6 }}>{label}</div>
      <div className="mono" style={{ fontSize: 24, color: accent ? 'var(--accent)' : 'var(--text)', lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

Object.assign(window, { LinkedInCampaigns, LinkedInCampaignBuilder });
