/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ============================================================
   CONSTANTS
   ============================================================ */
const STAGES = [
  { id: "new",         label: "New Inquiry",   color: "var(--stage-new)" },
  { id: "contacted",   label: "Contacted",     color: "var(--stage-contacted)" },
  { id: "proposal",    label: "Proposal Sent", color: "var(--stage-proposal)" },
  { id: "negotiation", label: "Negotiation",   color: "var(--stage-negotiation)" },
  { id: "won",         label: "Closed Won",    color: "var(--stage-won)" },
  { id: "lost",        label: "Closed Lost",   color: "var(--stage-lost)" },
];
const stageById = (id) => STAGES.find(s => s.id === id) || STAGES[0];

/* ============================================================
   ICONS (inline SVG, 1em scaled)
   ============================================================ */
const Icon = {
  Back:   (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M15 18l-6-6 6-6"/></svg>,
  Edit:   (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>,
  Phone:  (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.36 1.9.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0122 16.92z"/></svg>,
  Mail:   (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>,
  Audio:  (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>,
  Image:  (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21,15 16,10 5,21"/></svg>,
  Upload: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17,8 12,3 7,8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>,
  Plus:   (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
  Doc:    (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14,2 14,8 20,8"/></svg>,
  Trash:  (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="3,6 5,6 21,6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg>,
  Calendar:(p) => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
};

/* ============================================================
   API
   ============================================================ */
async function apiFetchLeads() {
  const res = await fetch("/api/leads");
  if (!res.ok) throw new Error("fetch leads failed");
  return res.json();
}

async function apiUpsertLead(lead) {
  const res = await fetch(`/api/leads/${lead.id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(lead),
  });
  if (!res.ok) throw new Error("save lead failed");
  return res.json();
}

async function apiDeleteLead(id) {
  const res = await fetch(`/api/leads/${id}`, { method: "DELETE" });
  if (!res.ok) throw new Error("delete lead failed");
}

/* ============================================================
   UTILS
   ============================================================ */
function fmtDate(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  const now = new Date();
  const diff = (now - d) / (1000 * 60 * 60 * 24);
  if (diff < 1) return "today";
  if (diff < 2) return "yesterday";
  if (diff < 7) return `${Math.floor(diff)}d ago`;
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short" });
}

function readFileAsDataURL(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

function newId() { return "ld_" + Math.random().toString(36).slice(2, 8); }
function fileId() { return "f_" + Math.random().toString(36).slice(2, 8); }

function useMediaQuery(q) {
  const [m, setM] = useState(() => typeof window !== "undefined" && window.matchMedia(q).matches);
  useEffect(() => {
    const mq = window.matchMedia(q);
    const h = (e) => setM(e.matches);
    mq.addEventListener("change", h);
    return () => mq.removeEventListener("change", h);
  }, [q]);
  return m;
}

/* ============================================================
   STAGE TAG
   ============================================================ */
function StageTag({ stage, large }) {
  const s = stageById(stage);
  return (
    <span className="stage-tag" style={{ "--stage-color": s.color }}>
      {s.label}
    </span>
  );
}

/* ============================================================
   APP
   ============================================================ */
function App() {
  const [leads, setLeads] = useState([]);
  const [loading, setLoading] = useState(true);
  const [view, setView] = useState({ name: "directory" });
  const [filter, setFilter] = useState("all");
  const [toast, setToast] = useState(null);
  const [lightbox, setLightbox] = useState(null);
  const isDesktop = useMediaQuery("(min-width: 900px)");

  useEffect(() => {
    apiFetchLeads()
      .then(data => { setLeads(data); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  function showToast(msg) {
    setToast(msg);
    setTimeout(() => setToast(null), 1800);
  }

  async function upsertLead(lead) {
    const saved = await apiUpsertLead(lead);
    setLeads(prev => {
      const exists = prev.find(l => l.id === saved.id);
      if (exists) return prev.map(l => l.id === saved.id ? saved : l);
      return [saved, ...prev];
    });
  }

  async function deleteLead(id) {
    await apiDeleteLead(id);
    setLeads(prev => prev.filter(l => l.id !== id));
  }

  const counts = useMemo(() => {
    const c = { all: leads.length };
    STAGES.forEach(s => c[s.id] = leads.filter(l => l.stage === s.id).length);
    return c;
  }, [leads]);

  const filtered = useMemo(() => {
    return filter === "all" ? leads : leads.filter(l => l.stage === filter);
  }, [leads, filter]);

  const currentLead = view.id ? leads.find(l => l.id === view.id) : null;

  // On mobile: rail is hidden when a lead/form is open. Main pane is hidden when on directory.
  // On desktop: both are always visible.
  const railHidden = !isDesktop && view.name !== "directory";
  const mainActive = isDesktop || view.name !== "directory";

  function openLead(id) {
    setView({ name: "detail", id });
  }
  function openNew() {
    setView({ name: "form" });
  }
  function openEdit(id) {
    setView({ name: "form", id });
  }
  function closeMain() {
    setView({ name: "directory" });
  }

  if (loading) {
    return (
      <div className="stage" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100vh" }}>
        <div style={{ fontFamily: "var(--mono)", color: "var(--text-faint)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase" }}>
          Loading…
        </div>
      </div>
    );
  }

  return (
    <div className="stage">
      <div className="app-shell" data-screen-label="App">
        <aside className={"app-rail" + (railHidden ? " is-hidden" : "")}>
          <Header onNew={openNew} />
          <div className="rail-scroll">
            <DirectoryView
              leads={filtered}
              allCount={leads.length}
              counts={counts}
              filter={filter}
              setFilter={setFilter}
              onOpen={openLead}
              selectedId={view.id}
            />
          </div>
        </aside>

        <main
          className={"app-main" + (mainActive ? " is-active" : "")}
          data-screen-label={
            view.name === "detail" ? "02 Detail" :
            view.name === "form" ? "03 Form" : "Main"
          }
        >
          {view.name === "form" ? (
            <FormView
              key={"form-" + (currentLead?.id || "new")}
              lead={currentLead}
              onCancel={() => setView(currentLead ? { name: "detail", id: currentLead.id } : { name: "directory" })}
              onSave={(lead) => {
                upsertLead(lead);
                setView({ name: "detail", id: lead.id });
                showToast(currentLead ? "Lead updated" : "Lead saved");
              }}
            />
          ) : view.name === "detail" && currentLead ? (
            <DetailView
              key={"detail-" + currentLead.id}
              lead={currentLead}
              isDesktop={isDesktop}
              onBack={closeMain}
              onEdit={() => openEdit(currentLead.id)}
              onDelete={() => {
                deleteLead(currentLead.id);
                closeMain();
                showToast("Lead deleted");
              }}
              onOpenImage={(src) => setLightbox(src)}
            />
          ) : (
            <EmptyMain onNew={openNew} count={leads.length} />
          )}
        </main>

        {view.name === "directory" && !isDesktop && (
          <button className="fab" onClick={openNew} aria-label="Add lead">
            <Icon.Plus />
          </button>
        )}

        {toast && <div className="toast">{toast}</div>}

        {lightbox && (
          <div className="lightbox" onClick={() => setLightbox(null)}>
            <button className="close" onClick={() => setLightbox(null)}>×</button>
            <img src={lightbox} alt="" />
          </div>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   EMPTY MAIN PANE (desktop, nothing selected)
   ============================================================ */
function EmptyMain({ onNew, count }) {
  return (
    <div className="empty-main">
      <div>
        <div className="glyph">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
            <polyline points="14,2 14,8 20,8"/>
            <line x1="9" y1="13" x2="15" y2="13"/>
            <line x1="9" y1="17" x2="15" y2="17"/>
          </svg>
        </div>
        <h2>Pick a lead.</h2>
        <p>Choose any entry from the list to open its detail view —<br/>or start a new one from the top right.</p>
        <div className="marks">// {count} tracked in this pipeline</div>
      </div>
    </div>
  );
}

/* ============================================================
   HEADER
   ============================================================ */
function Header({ onNew }) {
  const today = new Date().toLocaleDateString("en-IN", { day: "2-digit", month: "short" }).toUpperCase();
  return (
    <header className="app-header">
      <div className="brand">
        <img src="assets/weinnovatee-logo.jpeg" alt="weinnovatee" />
        <span className="tag">LEADLOG · personal CRM</span>
      </div>
      <button className="new-lead-btn" onClick={onNew}>
        <Icon.Plus style={{ width: 14, height: 14 }} /> New
      </button>
      <div className="meta">
        <span className="dot"></span>{today}
      </div>
    </header>
  );
}

/* ============================================================
   DIRECTORY VIEW
   ============================================================ */
function DirectoryView({ leads, allCount, counts, filter, setFilter, onOpen, selectedId }) {
  const totalOpen = leads.filter(l => l.stage !== "won" && l.stage !== "lost").length;
  const avgProb = leads.length
    ? Math.round(leads.reduce((s, l) => s + (l.probability || 0), 0) / leads.length)
    : 0;

  return (
    <div className="view">
      <div className="directory-head">
        <p className="eyebrow">// PIPELINE — 2026 Q2</p>
        <h1>Your leads.</h1>
        <p className="sub">
          <b>{allCount}</b> tracked · <b>{totalOpen}</b> open · avg close <b>{avgProb}%</b>
        </p>
      </div>

      <div className="filter-bar">
        <button
          className={"filter-pill" + (filter === "all" ? " active" : "")}
          onClick={() => setFilter("all")}
        >
          All <span className="count">{counts.all}</span>
        </button>
        {STAGES.map(s => (
          <button
            key={s.id}
            className={"filter-pill" + (filter === s.id ? " active" : "")}
            onClick={() => setFilter(s.id)}
          >
            {s.label} <span className="count">{counts[s.id] || 0}</span>
          </button>
        ))}
      </div>

      {leads.length === 0 ? (
        <div className="empty-state">
          <div className="title">Nothing here.</div>
          <div>No leads in this stage yet.</div>
        </div>
      ) : (
        <div className="lead-list">
          {leads.map(l => (
            <LeadCard
              key={l.id}
              lead={l}
              selected={l.id === selectedId}
              onOpen={() => onOpen(l.id)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function LeadCard({ lead, onOpen, selected }) {
  const s = stageById(lead.stage);
  const attachCount = (lead.audio?.length || 0) + (lead.images?.length || 0);
  return (
    <button
      className={"lead-card" + (selected ? " is-selected" : "")}
      style={{ "--stage-color": s.color }}
      onClick={onOpen}
    >
      <div className="name">{lead.name}</div>
      <div className="company">{lead.company}</div>
      <div className="prob">
        <div className="pct">{lead.probability}<span style={{fontSize:"12px",color:"var(--text-faint)"}}>%</span></div>
        <div className="lbl">close prob.</div>
      </div>
      <div className="footer">
        <StageTag stage={lead.stage} />
        <div className="meta-row">
          {attachCount > 0 && (
            <>
              <span>◴ {attachCount} attached</span>
              <span className="sep">·</span>
            </>
          )}
          <span><Icon.Calendar style={{ display: "inline", verticalAlign: "-2px", marginRight: 4 }} />{fmtDate(lead.updatedAt)}</span>
        </div>
      </div>
    </button>
  );
}

/* ============================================================
   DETAIL VIEW
   ============================================================ */
function DetailView({ lead, onBack, onEdit, onDelete, onOpenImage }) {
  const audio = lead.audio || [];
  const images = lead.images || [];

  return (
    <div className="view">
      <div className="detail-head">
        <button className="icon-btn" onClick={onBack} aria-label="Back">
          <Icon.Back />
        </button>
        <button className="icon-btn text" onClick={onEdit}>
          <Icon.Edit /> Edit
        </button>
      </div>

      <div className="detail-hero">
        <div className="lead-id">// {lead.id.toUpperCase()} · added {fmtDate(lead.createdAt)}</div>
        <h1 className="name">{lead.name}</h1>
        <div className="company">{lead.company}</div>
        <div className="contact">
          {lead.phone && (
            <a href={`tel:${lead.phone}`}><Icon.Phone /> {lead.phone}</a>
          )}
          {lead.email && (
            <a href={`mailto:${lead.email}`}><Icon.Mail /> {lead.email}</a>
          )}
        </div>
      </div>

      <div className="detail-stats">
        <div className="stage-wrap">
          <div className="label">Stage</div>
          <StageTag stage={lead.stage} />
        </div>
        <div className="prob-block">
          <div className="top">
            <span className="label">Closing Probability</span>
            <span className="pct">{lead.probability}%</span>
          </div>
          <div className="prob-bar">
            <div className="fill" style={{ width: `${lead.probability}%` }} />
          </div>
        </div>
      </div>

      <section className="section">
        <div className="section-head">
          <h2>Call recordings</h2>
          <span className="count-chip">{audio.length} files</span>
        </div>
        {audio.length === 0 ? (
          <div className="empty-inline">No recordings attached yet.</div>
        ) : (
          audio.map(a => (
            <div key={a.id} className="audio-item">
              <div className="label-row">
                <div className="nm"><Icon.Audio /><span>{a.name}</span></div>
                <div className="dur">{a.size ? formatBytes(a.size) : ""}</div>
              </div>
              <audio src={a.data} controls preload="metadata" />
            </div>
          ))
        )}
      </section>

      <section className="section">
        <div className="section-head">
          <h2>Reference images</h2>
          <span className="count-chip">{images.length} files</span>
        </div>
        {images.length === 0 ? (
          <div className="empty-inline">No images attached yet.</div>
        ) : (
          <div className="img-grid">
            {images.map(img => (
              <div key={img.id} className="img-tile" onClick={() => onOpenImage(img.data)}>
                <img src={img.data} alt={img.name} />
              </div>
            ))}
          </div>
        )}
      </section>

      <section className="section">
        <div className="section-head">
          <h2>My thoughts</h2>
        </div>
        {lead.notes ? (
          <div className="notes-block">
            <span className="quote-mark">“</span>{lead.notes}
          </div>
        ) : (
          <div className="empty-inline">No notes yet. Tap Edit to add.</div>
        )}
        <button className="danger-btn" onClick={() => {
          if (window.confirm(`Delete ${lead.name}? This can't be undone.`)) onDelete();
        }}>
          <Icon.Trash style={{ marginRight: 8, verticalAlign: "-2px" }} /> Delete lead
        </button>
      </section>

      <div className="detail-foot">
        <span>Updated {fmtDate(lead.updatedAt)}</span>
        <span>{lead.id}</span>
      </div>
    </div>
  );
}

function formatBytes(b) {
  if (!b) return "";
  if (b < 1024) return b + " B";
  if (b < 1024 * 1024) return (b / 1024).toFixed(1) + " KB";
  return (b / 1024 / 1024).toFixed(1) + " MB";
}

/* ============================================================
   FORM VIEW
   ============================================================ */
function FormView({ lead, onCancel, onSave }) {
  const isEdit = !!lead;
  const [name, setName] = useState(lead?.name || "");
  const [company, setCompany] = useState(lead?.company || "");
  const [phone, setPhone] = useState(lead?.phone || "");
  const [email, setEmail] = useState(lead?.email || "");
  const [stage, setStage] = useState(lead?.stage || "new");
  const [probability, setProbability] = useState(lead?.probability ?? 25);
  const [notes, setNotes] = useState(lead?.notes || "");
  const [audio, setAudio] = useState(lead?.audio || []);
  const [images, setImages] = useState(lead?.images || []);
  const [busy, setBusy] = useState(false);

  const audioInput = useRef(null);
  const imageInput = useRef(null);

  async function handleAudio(e) {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    setBusy(true);
    const items = [];
    for (const f of files) {
      try {
        const data = await readFileAsDataURL(f);
        items.push({ id: fileId(), name: f.name, size: f.size, type: f.type, data });
      } catch (err) {}
    }
    setAudio(prev => [...prev, ...items]);
    setBusy(false);
    e.target.value = "";
  }

  async function handleImages(e) {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    setBusy(true);
    const items = [];
    for (const f of files) {
      try {
        const data = await readFileAsDataURL(f);
        items.push({ id: fileId(), name: f.name, size: f.size, type: f.type, data });
      } catch (err) {}
    }
    setImages(prev => [...prev, ...items]);
    setBusy(false);
    e.target.value = "";
  }

  function removeAudio(id) { setAudio(a => a.filter(x => x.id !== id)); }
  function removeImage(id) { setImages(a => a.filter(x => x.id !== id)); }

  function submit() {
    if (!name.trim()) {
      alert("Client name is required.");
      return;
    }
    const payload = {
      id: lead?.id || newId(),
      name: name.trim(),
      company: company.trim(),
      phone: phone.trim(),
      email: email.trim(),
      stage,
      probability: Number(probability),
      notes,
      audio,
      images,
      createdAt: lead?.createdAt,
    };
    onSave(payload);
  }

  return (
    <div className="view">
      <div className="form-head">
        <button className="icon-btn" onClick={onCancel} aria-label="Back">
          <Icon.Back />
        </button>
        <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", color: "var(--text-faint)", textTransform: "uppercase" }}>
          {isEdit ? "Editing" : "New entry"}
        </div>
      </div>

      <div className="form-body">
        <p className="form-eyebrow">// {isEdit ? lead.id.toUpperCase() : "DRAFT"}</p>
        <h1>{isEdit ? "Edit lead" : "Log a lead"}</h1>

        <div className="field">
          <label>Client Name <span className="req">*</span></label>
          <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Arjun Mehta" />
        </div>

        <div className="field">
          <label>Company</label>
          <input type="text" value={company} onChange={e => setCompany(e.target.value)} placeholder="e.g. Lumen Cargo Logistics" />
        </div>

        <div className="field-row">
          <div className="field">
            <label>Phone</label>
            <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="+91 9…" />
          </div>
          <div className="field">
            <label>Email</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="name@co.com" />
          </div>
        </div>

        <div className="field">
          <label>Pipeline Stage</label>
          <select value={stage} onChange={e => setStage(e.target.value)}>
            {STAGES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
        </div>

        <div className="field">
          <label>Closing Probability</label>
          <div className="slider-row">
            <input
              type="range" min="0" max="100" step="5"
              value={probability}
              onChange={e => setProbability(e.target.value)}
              style={{ "--slider-pct": probability + "%" }}
            />
            <span className="val">{probability}%</span>
          </div>
        </div>

        <div className="field">
          <label>Call Recordings</label>
          <button className="upload-zone" type="button" onClick={() => audioInput.current?.click()}>
            <Icon.Upload />
            <div>Tap to attach audio</div>
            <div className="hint">mp3 · m4a · wav</div>
          </button>
          <input ref={audioInput} type="file" accept="audio/*,.mp3,.m4a,.wav" multiple style={{ display: "none" }} onChange={handleAudio} />
          {audio.length > 0 && (
            <div className="attached-list">
              {audio.map(a => (
                <div className="att" key={a.id}>
                  <div className="nm"><Icon.Audio /><span>{a.name}</span></div>
                  <button className="rm" onClick={() => removeAudio(a.id)} aria-label="Remove">×</button>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="field">
          <label>Reference Images</label>
          <button className="upload-zone" type="button" onClick={() => imageInput.current?.click()}>
            <Icon.Image />
            <div>Tap to attach images</div>
            <div className="hint">jpg · png · pdf</div>
          </button>
          <input ref={imageInput} type="file" accept="image/*,.pdf" multiple style={{ display: "none" }} onChange={handleImages} />
          {images.length > 0 && (
            <div className="img-attached">
              {images.map(img => (
                <div className="thumb" key={img.id}>
                  <img src={img.data} alt={img.name} />
                  <button className="rm" onClick={() => removeImage(img.id)} aria-label="Remove">×</button>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="field">
          <label>My Thoughts / Notes</label>
          <textarea
            value={notes}
            onChange={e => setNotes(e.target.value)}
            placeholder="What did they say? What's the pitch? What did I learn?"
            rows={6}
          />
        </div>
      </div>

      <div className="save-bar">
        <button className="ghost" onClick={onCancel}>Cancel</button>
        <button className="primary" onClick={submit} disabled={busy}>
          {busy ? "Working…" : (isEdit ? "Save changes" : "Save lead")}
        </button>
      </div>
    </div>
  );
}

/* ============================================================
   MOUNT
   ============================================================ */
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
