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

const STAGES_BY_PIPELINE = {
  outbound: ['New', 'Request Sent', 'Connected', 'Messaged', 'Replied', 'Interested', 'Discovery Call', 'Strategy Session', 'Follow Up', 'Deposit Taken', 'Deal Closed', 'Lost', 'Nurture'],
  inbound: ['New Lead', 'Qualified', 'Contacted', 'Replied', 'Discovery Call', 'Strategy Session', 'Follow Up', 'Deposit Taken', 'Deal Closed', 'Lost', 'Nurture'],
};
const INBOUND_SOURCES = new Set(['meta-ads-fb', 'meta-ads-ig', 'referral', 'funnel-form', 'imported-list', 'inbound-other']);

function pipelineFor(source) {
  return INBOUND_SOURCES.has(source) ? 'inbound' : 'outbound';
}
function _initialsC(name) {
  if (!name) return '?';
  const parts = String(name).replace(/[._@-]/g, ' ').split(/\s+/).filter(Boolean);
  if (!parts.length) return name.slice(0, 2).toUpperCase();
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
function _colorC(s) {
  const palette = ['#22c55e', '#3b82f6', '#a855f7', '#f97316', '#eab308', '#ec4899', '#06b6d4', '#84cc16'];
  let h = 0;
  for (let i = 0; i < (s || '').length; i++) h = ((h << 5) - h) + s.charCodeAt(i);
  return palette[Math.abs(h) % palette.length];
}
function _relC(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'now';
  if (diff < 3600) return `${Math.round(diff / 60)}m`;
  if (diff < 86400) return `${Math.round(diff / 3600)}h`;
  if (diff < 86400 * 7) return `${Math.round(diff / 86400)}d`;
  return d.toLocaleDateString();
}

function Contact({ contactId, goto }) {
  const [contact, setContact] = useState(null);
  const [tab, setTab] = useState('timeline');
  const [deals, setDeals] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [notes, setNotes] = useState([]);
  const [timeline, setTimeline] = useState([]);
  const [error, setError] = useState(null);

  const reloadAll = () => {
    if (!contactId) return;
    fetch(`/api/contacts/${contactId}`, { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then(setContact)
      .catch((e) => setError(String(e)));
    fetch(`/api/deals?contact_id=${contactId}`, { credentials: 'include' }).then((r) => r.json()).then((d) => setDeals(d.items || []));
    fetch(`/api/tasks?contact_id=${contactId}&only_open=false`, { credentials: 'include' }).then((r) => r.json()).then((d) => setTasks(d.items || []));
    fetch(`/api/notes?contact_id=${contactId}`, { credentials: 'include' }).then((r) => r.json()).then((d) => setNotes(d.items || []));
    fetch(`/api/lead-events/contact/${contactId}/timeline`, { credentials: 'include' }).then((r) => r.json()).then((d) => setTimeline(d.items || []));
  };

  useEffect(reloadAll, [contactId]);

  const onStageChange = async (newStage) => {
    if (!contact) return;
    setContact({ ...contact, pipeline_stage: newStage });
    await fetch(`/api/pipeline/contacts/${contact.id}/stage`, {
      method: 'POST',
      credentials: 'include',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ stage: newStage }),
    });
    reloadAll();
  };

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

  const pipeline = pipelineFor(contact.source);
  const stages = STAGES_BY_PIPELINE[pipeline];
  const channelKinds = [
    contact.linkedin_url ? { kind: 'linkedin', value: contact.linkedin_url } : null,
    contact.whatsapp_number ? { kind: 'whatsapp', value: contact.whatsapp_number } : null,
    contact.instagram_handle ? { kind: 'instagram', value: '@' + contact.instagram_handle } : null,
    contact.email ? { kind: 'email', value: contact.email } : null,
  ].filter(Boolean);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr 320px', height: '100%', overflow: 'hidden' }}>
      {/* Left rail */}
      <div style={{ borderRight: '1px solid var(--divider)', overflowY: 'auto', padding: 24 }}>
        <button className="btn btn-ghost btn-sm" style={{ marginBottom: 16, padding: '4px 6px' }} onClick={() => goto('contacts')}>
          <Icon name="chevLeft" size={12} /> Contacts
        </button>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 10, marginBottom: 20 }}>
          <Avatar name={contact.name || '?'} initials={_initialsC(contact.name)} color={_colorC(contact.name || contact.id)} size="xl" />
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em' }}>{contact.name || '(unnamed)'}</div>
            <div style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{contact.title || '—'}</div>
            <div style={{ fontSize: 12, color: 'var(--accent)' }}>{contact.company || '—'}</div>
          </div>
          <span style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>{contact.temperature}</span>
        </div>

        {channelKinds.length > 0 && (
          <div style={{ marginBottom: 18 }}>
            <div className="label" style={{ marginBottom: 8 }}>Channels</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {channelKinds.map((ch) => (
                <div key={ch.kind} style={{ padding: '6px 8px', display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, border: '1px solid var(--divider)' }}>
                  <ChannelIcon kind={ch.kind} size={12} />
                  <span style={{ flex: 1, color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ch.value}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ marginBottom: 18 }}>
          <div className="label" style={{ marginBottom: 8 }}>Source</div>
          <span style={{ fontSize: 12, color: 'var(--text)', textTransform: 'capitalize' }}>{contact.source || '—'}</span>
          {contact.utm && Object.keys(contact.utm).length > 0 && (
            <div style={{ marginTop: 8, fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
              {Object.entries(contact.utm).filter(([, v]) => v).map(([k, v]) => <div key={k}>{k}={v}</div>)}
            </div>
          )}
        </div>

        <div style={{ marginBottom: 18 }}>
          <div className="label" style={{ marginBottom: 8 }}>Pipeline Stage <span style={{ marginLeft: 4, color: 'var(--text-dim)' }}>({pipeline})</span></div>
          <select
            className="input"
            value={contact.pipeline_stage}
            onChange={(e) => onStageChange(e.target.value)}
          >
            {stages.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      {/* Middle */}
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div className="tabs">
          {[
            { id: 'timeline', label: 'Timeline' },
            { id: 'tasks', label: 'Tasks', count: tasks.filter((t) => !t.done).length || null },
            { id: 'notes', label: 'Notes', count: notes.length || null },
          ].map((t) => (
            <div key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
              {t.label}
              {t.count != null && <span className="tab-count">{t.count}</span>}
            </div>
          ))}
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
          {tab === 'timeline' && <Timeline items={timeline} />}
          {tab === 'tasks' && <Tasks tasks={tasks} contactId={contactId} reload={reloadAll} />}
          {tab === 'notes' && <Notes notes={notes} contactId={contactId} reload={reloadAll} />}
        </div>
      </div>

      {/* Right rail: deals */}
      <div style={{ borderLeft: '1px solid var(--divider)', overflowY: 'auto', padding: 20 }}>
        <div className="label" style={{ marginBottom: 10 }}>Deals</div>
        {deals.length === 0 && (
          <div style={{ fontSize: 12, color: 'var(--text-dim)', padding: '12px 0' }}>No deals yet.</div>
        )}
        {deals.map((d) => (
          <div key={d.id} className="card" style={{ padding: 12, marginBottom: 8 }}>
            <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 4 }}>{d.name}</div>
            <div className="mono" style={{ fontSize: 16, color: 'var(--accent)' }}>AED {fmtAED(d.value_aed)}</div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 4 }}>
              {d.type} · {d.probability}% · {d.stage}
            </div>
          </div>
        ))}
        <NewDealButton contactId={contactId} pipeline={pipeline} reload={reloadAll} />
      </div>
    </div>
  );
}

function Timeline({ items }) {
  if (!items.length) {
    return <div style={{ color: 'var(--text-dim)', fontSize: 13 }}>No activity yet.</div>;
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      {items.map((a) => (
        <div key={`${a.kind}-${a.id}`} style={{ display: 'flex', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--divider)' }}>
          <div style={{ width: 8, height: 8, borderRadius: '50%', background: a.kind === 'message' ? 'var(--accent)' : 'var(--text-dim)', marginTop: 7, flexShrink: 0 }}></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, color: 'var(--text)', whiteSpace: 'pre-wrap' }}>{a.summary}</div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 4 }} className="mono">{a.subkind} · {_relC(a.at)}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function Tasks({ tasks, contactId, reload }) {
  const [title, setTitle] = useState('');
  const add = async () => {
    if (!title.trim()) return;
    await fetch('/api/tasks', {
      method: 'POST',
      credentials: 'include',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ contact_id: contactId, title }),
    });
    setTitle('');
    reload();
  };
  const toggle = async (t) => {
    await fetch(`/api/tasks/${t.id}`, {
      method: 'PATCH',
      credentials: 'include',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ done: !t.done }),
    });
    reload();
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        <input
          className="input"
          placeholder="Add a task and press Enter"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && add()}
          style={{ flex: 1 }}
        />
        <button className="btn btn-primary" onClick={add}><Icon name="plus" size={11} /> Add</button>
      </div>
      {tasks.length === 0 && <div style={{ color: 'var(--text-dim)', fontSize: 13 }}>No tasks yet.</div>}
      {tasks.map((t) => (
        <div key={t.id} style={{ display: 'flex', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--divider)', alignItems: 'center' }}>
          <input type="checkbox" checked={t.done} onChange={() => toggle(t)} />
          <span style={{ flex: 1, fontSize: 13, color: t.done ? 'var(--text-dim)' : 'var(--text)', textDecoration: t.done ? 'line-through' : 'none' }}>{t.title}</span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{_relC(t.created_at)}</span>
        </div>
      ))}
    </div>
  );
}

function Notes({ notes, contactId, reload }) {
  const [body, setBody] = useState('');
  const add = async () => {
    if (!body.trim()) return;
    await fetch('/api/notes', {
      method: 'POST',
      credentials: 'include',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ contact_id: contactId, body }),
    });
    setBody('');
    reload();
  };
  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <textarea
          className="textarea"
          placeholder="Write a note (markdown supported)…"
          value={body}
          onChange={(e) => setBody(e.target.value)}
          rows={3}
          style={{ width: '100%', marginBottom: 8 }}
        />
        <button className="btn btn-primary" onClick={add}><Icon name="plus" size={11} /> Save note</button>
      </div>
      {notes.length === 0 && <div style={{ color: 'var(--text-dim)', fontSize: 13 }}>No notes yet.</div>}
      {notes.map((n) => (
        <div key={n.id} className="card" style={{ padding: 12, marginBottom: 8 }}>
          <div style={{ fontSize: 13, color: 'var(--text)', whiteSpace: 'pre-wrap' }}>{n.body}</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 6 }}>{_relC(n.created_at)}</div>
        </div>
      ))}
    </div>
  );
}

function NewDealButton({ contactId, pipeline, reload }) {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState('');
  const [value, setValue] = useState('');
  const [type, setType] = useState('one-off');
  const submit = async () => {
    if (!name.trim()) return;
    await fetch('/api/deals', {
      method: 'POST',
      credentials: 'include',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        contact_id: contactId,
        name,
        value_aed: parseFloat(value || '0'),
        type,
        pipeline,
      }),
    });
    setName(''); setValue(''); setType('one-off');
    setOpen(false);
    reload();
  };
  if (!open) {
    return <button className="btn btn-sm" style={{ width: '100%', marginTop: 8 }} onClick={() => setOpen(true)}><Icon name="plus" size={11} /> New deal</button>;
  }
  return (
    <div className="card" style={{ padding: 12, marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <input className="input" placeholder="Deal name" value={name} onChange={(e) => setName(e.target.value)} />
      <input className="input" placeholder="Value (AED)" type="number" value={value} onChange={(e) => setValue(e.target.value)} />
      <select className="input" value={type} onChange={(e) => setType(e.target.value)}>
        <option value="one-off">One-off</option>
        <option value="retainer-monthly">Retainer (monthly)</option>
        <option value="retainer-quarterly">Retainer (quarterly)</option>
      </select>
      <div style={{ display: 'flex', gap: 6 }}>
        <button className="btn btn-sm" onClick={() => setOpen(false)} style={{ flex: 1 }}>Cancel</button>
        <button className="btn btn-primary btn-sm" onClick={submit} style={{ flex: 1 }}>Save</button>
      </div>
    </div>
  );
}

/* ============================================================
   ACCOUNT (placeholder — full wiring in Phase 2)
   ============================================================ */
function Account({ accountId, goto }) {
  return (
    <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)' }}>
      <button className="btn btn-ghost btn-sm" style={{ marginBottom: 16 }} onClick={() => goto('accounts')}>
        <Icon name="chevLeft" size={12} /> Accounts
      </button>
      <div style={{ fontSize: 13 }}>Account detail page wires up in Phase 2.</div>
      <div style={{ fontSize: 11, marginTop: 8 }} className="mono">id: {accountId}</div>
    </div>
  );
}

Object.assign(window, { Contact, Account });
