import { useState, useRef } from “react”;

// ─── Constants ───
const TEMP_OPTIONS = [
{ value: “hot”, label: “🔥 Hot”, color: “#E8572A” },
{ value: “warm”, label: “☀️ Warm”, color: “#FF9F1C” },
{ value: “cool”, label: “💧 Cool”, color: “#2EC4B6” },
];
const REP_ACTIONS = [
{ value: “send_info”, label: “📩 Send info/asset” },
{ value: “book_meeting”, label: “📅 Book a meeting” },
{ value: “intro”, label: “🤝 Make an intro” },
{ value: “proposal”, label: “📝 Send proposal” },
{ value: “personal_note”, label: “✉️ Personal follow-up” },
{ value: “none”, label: “— None” },
];
const MKTG_ACTIONS = [
{ value: “nurture”, label: “📬 Add to post-event nurture” },
{ value: “help_followup”, label: “🙋 Help me with my follow-up” },
{ value: “pause_30”, label: “⏸️ Pause nurture 30 days” },
{ value: “none”, label: “— None” },
];

const fmt = d => d.toLocaleTimeString([], { hour: “numeric”, minute: “2-digit” });
const durMin = (s, e) => e ? Math.round((e - s) / 60000) : null;

// ─── Shared UI ───
const Pill = ({ selected, onClick, children, color }) => (
<button onClick={onClick} style={{
padding: “9px 14px”, borderRadius: 10,
border: selected ? `2px solid ${color || "#FF6B35"}` : “2px solid #ebebeb”,
background: selected ? `${color || "#FF6B35"}0e` : “#fafafa”,
color: selected ? (color || “#FF6B35”) : “#888”,
fontSize: 12, fontWeight: 700, cursor: “pointer”, transition: “all 0.15s”,
fontFamily: “‘DM Sans’, sans-serif”,
}}>{children}</button>
);

const SectionLabel = ({ color, children }) => (

  <div style={{
    fontSize: 10, fontWeight: 800, color, textTransform: "uppercase",
    letterSpacing: 1.5, marginTop: 14, marginBottom: 8,
    display: "flex", alignItems: "center", gap: 6,
  }}>
    <div style={{ width: 12, height: 2, background: color, borderRadius: 1 }} />
    {children}
  </div>
);

const Input = ({ value, onChange, placeholder, type, autoComplete, onFocus, onBlur }) => (
<input value={value} onChange={onChange} placeholder={placeholder}
type={type || “text”} autoComplete={autoComplete}
style={{
width: “100%”, padding: “12px 14px”, border: “2px solid #e8e8e8”, borderRadius: 10,
fontSize: 15, marginBottom: 8, outline: “none”, background: “#fafafa”,
fontFamily: “‘DM Sans’, sans-serif”, boxSizing: “border-box”,
}}
onFocus={e => e.target.style.borderColor = “#FF6B35”}
onBlur={e => e.target.style.borderColor = “#e8e8e8”}
/>
);

// ─── Lead Card ───
function LeadCard({ lead, onEnd, isActive }) {
const dur = durMin(lead.startTime, lead.endTime);
const temp = TEMP_OPTIONS.find(t => t.value === lead.temperature);
const rActs = REP_ACTIONS.filter(r => lead.repActions?.includes(r.value) && r.value !== “none”);
const mActs = MKTG_ACTIONS.filter(m => lead.mktgActions?.includes(m.value) && m.value !== “none”);

return (
<div style={{
background: “#fff”, borderRadius: 14, padding: “14px 16px”, marginBottom: 8,
borderLeft: `4px solid ${temp ? temp.color : "#ddd"}`,
boxShadow: isActive ? “0 4px 20px #FF6B3533” : “0 1px 3px #0001”,
}}>
<div style={{ display: “flex”, justifyContent: “space-between”, alignItems: “flex-start” }}>
<div>
<div style={{ fontSize: 15, fontWeight: 700, color: “#1a1a2e” }}>{lead.name || “No name”}</div>
{lead.company && <div style={{ fontSize: 12, color: “#666”, marginTop: 1 }}>{lead.company}</div>}
</div>
<div style={{ textAlign: “right” }}>
<div style={{ fontSize: 10, color: “#999” }}>{fmt(lead.startTime)}</div>
{dur !== null && <div style={{ fontSize: 10, color: “#2EC4B6”, fontWeight: 700 }}>{dur} min</div>}
{isActive && <div style={{ fontSize: 10, color: “#FF6B35”, fontWeight: 700 }}>● LIVE</div>}
{lead.source === “import” && <div style={{ fontSize: 9, color: “#999”, fontWeight: 600 }}>IMPORTED</div>}
</div>
</div>
<div style={{ display: “flex”, gap: 5, marginTop: 8, flexWrap: “wrap” }}>
{temp && <span style={{ fontSize: 10, fontWeight: 700, padding: “2px 8px”, borderRadius: 20, background: `${temp.color}12`, color: temp.color }}>{temp.label}</span>}
{rActs.map(a => <span key={a.value} style={{ fontSize: 10, fontWeight: 600, padding: “2px 8px”, borderRadius: 8, background: “#9B5DE510”, color: “#7B4BC4” }}>{a.label}</span>)}
{mActs.map(a => <span key={a.value} style={{ fontSize: 10, fontWeight: 600, padding: “2px 8px”, borderRadius: 8, background: “#1A936F10”, color: “#1A936F” }}>{a.label}</span>)}
</div>
{lead.repNote && <div style={{ fontSize: 11, color: “#9B5DE5”, marginTop: 5, fontStyle: “italic” }}>”{lead.repNote}”</div>}
{lead.notes && <div style={{ fontSize: 11, color: “#888”, marginTop: 4, fontStyle: “italic” }}>{lead.notes}</div>}
{isActive && (
<button onClick={onEnd} style={{
marginTop: 10, width: “100%”, padding: “12px”, borderRadius: 10,
border: “none”, background: “#1a1a2e”, color: “#fff”,
fontSize: 13, fontWeight: 700, cursor: “pointer”,
}}>End Conversation ✓</button>
)}
</div>
);
}

// ─── Dashboard ───
function Dashboard({ leads, eventName, costs, setCosts }) {
const reps = […new Set(leads.map(l => l.staffName || “Unassigned”))];
const totalLeads = leads.length;
const hot = leads.filter(l => l.temperature === “hot”).length;
const warm = leads.filter(l => l.temperature === “warm”).length;
const cool = totalLeads - hot - warm;
const qualifiedLeads = hot + warm;
const avgDwell = leads.filter(l => l.endTime).length > 0
? Math.round(leads.filter(l => l.endTime).reduce((s, l) => s + durMin(l.startTime, l.endTime), 0) / leads.filter(l => l.endTime).length)
: null;
const repOwes = leads.filter(l => l.repActions?.length > 0).length;
const mktgQueue = leads.filter(l => l.mktgActions?.length > 0).length;
const helpRequests = leads.filter(l => l.mktgActions?.includes(“help_followup”)).length;

const totalCost = Object.values(costs).reduce((s, v) => s + (Number(v) || 0), 0);
const cpl = qualifiedLeads > 0 && totalCost > 0 ? Math.round(totalCost / qualifiedLeads) : null;
const grade = cpl === null ? { g: “—”, c: “#666” } : cpl <= 150 ? { g: “A+”, c: “#1A936F” } : cpl <= 250 ? { g: “A”, c: “#2EC4B6” } : cpl <= 400 ? { g: “B”, c: “#FF9F1C” } : cpl <= 600 ? { g: “C”, c: “#FF6B35” } : { g: “D”, c: “#E8572A” };

const Stat = ({ label, value, sub, color }) => (
<div style={{ flex: “1 1 140px”, background: “#ffffff0a”, borderRadius: 12, padding: “14px 14px”, border: “1px solid #ffffff11” }}>
<div style={{ fontSize: 9, fontWeight: 700, textTransform: “uppercase”, letterSpacing: 1.2, color: “#ffffff66”, marginBottom: 6 }}>{label}</div>
<div style={{ fontSize: 24, fontWeight: 800, color: color || “#fff”, fontFamily: “‘Outfit’, sans-serif” }}>{value}</div>
{sub && <div style={{ fontSize: 10, color: “#ffffff44”, marginTop: 2 }}>{sub}</div>}
</div>
);

const RepRow = ({ name }) => {
const rl = leads.filter(l => (l.staffName || “Unassigned”) === name);
const rHot = rl.filter(l => l.temperature === “hot”).length;
const rWarm = rl.filter(l => l.temperature === “warm”).length;
const rOwes = rl.filter(l => l.repActions?.length > 0).length;
const rDwell = rl.filter(l => l.endTime).length > 0
? Math.round(rl.filter(l => l.endTime).reduce((s, l) => s + durMin(l.startTime, l.endTime), 0) / rl.filter(l => l.endTime).length)
: null;

```
return (
  <div style={{
    background: "#ffffff08", borderRadius: 12, padding: "14px 16px", marginBottom: 8,
    border: "1px solid #ffffff0d",
  }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: "#fff" }}>{name}</div>
      <div style={{ fontSize: 20, fontWeight: 800, color: "#FF6B35", fontFamily: "'Outfit', sans-serif" }}>{rl.length}</div>
    </div>
    <div style={{ display: "flex", gap: 10, flexWrap: "wrap", fontSize: 11 }}>
      <span style={{ color: "#E8572A", fontWeight: 700 }}>🔥 {rHot}</span>
      <span style={{ color: "#FF9F1C", fontWeight: 700 }}>☀️ {rWarm}</span>
      <span style={{ color: "#2EC4B6", fontWeight: 700 }}>💧 {rl.length - rHot - rWarm}</span>
      {rDwell && <span style={{ color: "#ffffff55" }}>⏱ {rDwell} min avg</span>}
      {rOwes > 0 && <span style={{ color: "#9B5DE5" }}>⚡ {rOwes} follow-ups owed</span>}
    </div>
  </div>
);
```

};

const CostInput = ({ id, label }) => (
<div style={{ display: “flex”, alignItems: “center”, gap: 8, marginBottom: 6 }}>
<label style={{ fontSize: 12, color: “#ffffffaa”, flex: “1 1 140px”, fontWeight: 600 }}>{label}</label>
<div style={{ display: “flex”, alignItems: “center”, gap: 4 }}>
<span style={{ color: “#ffffff44”, fontSize: 13 }}>$</span>
<input value={costs[id] || “”} onChange={e => setCosts(p => ({ …p, [id]: e.target.value }))}
type=“number” placeholder=“0”
style={{
width: 100, padding: “8px 10px”, border: “1px solid #ffffff22”, borderRadius: 8,
fontSize: 14, background: “#ffffff0a”, color: “#fff”, outline: “none”,
fontFamily: “‘JetBrains Mono’, monospace”, textAlign: “right”,
}}
/>
</div>
</div>
);

return (
<div style={{ padding: “20px 16px 40px” }}>
{/* Hero grade */}
<div style={{
textAlign: “center”, padding: “24px 16px”, marginBottom: 20,
background: “linear-gradient(135deg, #ffffff08, #ffffff03)”, borderRadius: 18,
border: “1px solid #ffffff11”,
}}>
<div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 2, color: “#ffffff66”, textTransform: “uppercase”, marginBottom: 6 }}>
{eventName || “Event”} · Cost Per Qualified Lead
</div>
<div style={{ fontSize: 56, fontWeight: 900, color: grade.c, fontFamily: “‘Outfit’, sans-serif”, lineHeight: 1 }}>
{grade.g}
</div>
{cpl !== null && <div style={{ fontSize: 13, color: “#ffffffaa”, marginTop: 6 }}>${cpl} per qualified lead</div>}
{cpl === null && <div style={{ fontSize: 12, color: “#ffffff44”, marginTop: 6 }}>Add costs below to calculate grade</div>}
</div>

```
  {/* Stats grid */}
  <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 20 }}>
    <Stat label="Total Leads" value={totalLeads} color="#fff" />
    <Stat label="Qualified" value={qualifiedLeads} color="#2EC4B6" sub={`${hot} hot · ${warm} warm`} />
    <Stat label="Avg Dwell" value={avgDwell ? `${avgDwell}m` : "—"} color="#FF9F1C" />
    <Stat label="Follow-ups Owed" value={repOwes} color="#9B5DE5" sub={helpRequests > 0 ? `${helpRequests} need help` : ""} />
  </div>

  {/* Rep breakdown */}
  {reps.length > 0 && (
    <div style={{ marginBottom: 20 }}>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 2, color: "#ffffff55", textTransform: "uppercase", marginBottom: 10 }}>
        Activity by Rep
      </div>
      {reps.map(r => <RepRow key={r} name={r} />)}
    </div>
  )}

  {/* Cost inputs */}
  <div style={{
    background: "#ffffff06", borderRadius: 14, padding: "18px 16px",
    border: "1px solid #ffffff0d", marginBottom: 20,
  }}>
    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 2, color: "#ffffff55", textTransform: "uppercase", marginBottom: 12 }}>
      Event Investment
    </div>
    <CostInput id="booth" label="Booth & design" />
    <CostInput id="travel" label="Travel & lodging" />
    <CostInput id="staff" label="Staff time (loaded)" />
    <CostInput id="promo" label="Promo & swag" />
    <CostInput id="other" label="Other" />
    {totalCost > 0 && (
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, paddingTop: 10, borderTop: "1px solid #ffffff11" }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: "#ffffffaa" }}>Total</span>
        <span style={{ fontSize: 16, fontWeight: 800, color: "#fff", fontFamily: "'JetBrains Mono', monospace" }}>${totalCost.toLocaleString()}</span>
      </div>
    )}
  </div>

  {/* Marketing queue summary */}
  <div style={{
    background: "#1A936F11", borderRadius: 14, padding: "16px",
    border: "1px solid #1A936F22",
  }}>
    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 2, color: "#1A936F", textTransform: "uppercase", marginBottom: 8 }}>
      Marketing Queue
    </div>
    <div style={{ fontSize: 13, color: "#ffffffbb" }}>
      <strong>{leads.filter(l => l.mktgActions?.includes("nurture")).length}</strong> → post-event nurture
    </div>
    <div style={{ fontSize: 13, color: "#ffffffbb" }}>
      <strong>{helpRequests}</strong> → need follow-up help
    </div>
    <div style={{ fontSize: 13, color: "#ffffffbb" }}>
      <strong>{leads.filter(l => l.mktgActions?.includes("pause_30")).length}</strong> → paused 30 days
    </div>
  </div>

  {/* Footer */}
  <div style={{ textAlign: "center", marginTop: 28 }}>
    <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: 3, color: "#FF6B35", textTransform: "uppercase" }}>BoothSpark</div>
    <div style={{ fontSize: 10, color: "#ffffff33", marginTop: 3 }}>You're already in the room. Stop wasting it.</div>
  </div>
</div>
```

);
}

// ─── Main App ───
export default function BoothSparkApp() {
const [tab, setTab] = useState(“capture”); // capture | import | dashboard
const [leads, setLeads] = useState([]);
const [showForm, setShowForm] = useState(false);
const [activeId, setActiveId] = useState(null);
const [formStep, setFormStep] = useState(1);
const [costs, setCosts] = useState({});
const fileRef = useRef();

// Form fields
const [name, setName] = useState(””);
const [company, setCompany] = useState(””);
const [email, setEmail] = useState(””);
const [phone, setPhone] = useState(””);
const [temperature, setTemperature] = useState(””);
const [repActions, setRepActions] = useState([]);
const [repNote, setRepNote] = useState(””);
const [mktgActions, setMktgActions] = useState([]);
const [notes, setNotes] = useState(””);
const [eventName, setEventName] = useState(””);
const [staffName, setStaffName] = useState(””);

// Import state
const [importPreview, setImportPreview] = useState(null);
const [importMapping, setImportMapping] = useState({});
const [importCount, setImportCount] = useState(0);

const resetForm = () => {
setName(””); setCompany(””); setEmail(””); setPhone(””);
setTemperature(””); setRepActions([]); setRepNote(””);
setMktgActions([]); setNotes(””); setFormStep(1);
};

const toggle = (arr, setArr, val) => {
if (val === “none”) return setArr([“none”]);
const w = arr.filter(v => v !== “none”);
setArr(w.includes(val) ? w.filter(v => v !== val) : […w, val]);
};

const saveLead = () => {
const l = {
id: Date.now(), name, company, email, phone, temperature,
repActions: repActions.filter(v => v !== “none”), repNote,
mktgActions: mktgActions.filter(v => v !== “none”), notes,
startTime: new Date(), endTime: null, staffName, source: “manual”,
};
setLeads(p => [l, …p]);
setActiveId(l.id);
resetForm(); setShowForm(false);
};

const endConvo = id => {
setLeads(p => p.map(l => l.id === id ? { …l, endTime: new Date() } : l));
setActiveId(null);
};

// CSV Import
const handleFile = e => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = ev => {
const text = ev.target.result;
const lines = text.split(”\n”).map(l => l.split(”,”).map(c => c.replace(/^”|”$/g, “”).trim()));
if (lines.length < 2) return;
const headers = lines[0];
const rows = lines.slice(1).filter(r => r.some(c => c));
setImportPreview({ headers, rows });
// Auto-map common field names
const m = {};
const nameMap = { name: “name”, “full name”: “name”, “first name”: “name”, “contact name”: “name”, company: “company”, organization: “company”, email: “email”, “email address”: “email”, phone: “phone”, “phone number”: “phone” };
headers.forEach((h, i) => {
const key = h.toLowerCase().trim();
if (nameMap[key]) m[nameMap[key]] = i;
});
setImportMapping(m);
setImportCount(rows.length);
};
reader.readAsText(file);
};

const doImport = () => {
if (!importPreview) return;
const newLeads = importPreview.rows.map((row, i) => ({
id: Date.now() + i,
name: row[importMapping.name] || “”,
company: row[importMapping.company] || “”,
email: row[importMapping.email] || “”,
phone: row[importMapping.phone] || “”,
temperature: “”, repActions: [], repNote: “”, mktgActions: [], notes: “”,
startTime: new Date(), endTime: new Date(), staffName: staffName || “Import”,
source: “import”,
}));
setLeads(p => […newLeads, …p]);
setImportPreview(null); setImportCount(0);
};

const exportCSV = () => {
const h = [“bs_name”,“bs_company”,“bs_email”,“bs_phone”,“bs_temperature”,“bs_rep_actions”,“bs_rep_note”,“bs_mktg_actions”,“bs_notes”,“bs_start_time”,“bs_end_time”,“bs_dwell_min”,“bs_staff”,“bs_event”,“bs_source”];
const rows = leads.map(l => [
`"${(l.name||"").replace(/"/g,'""')}"`, `"${(l.company||"").replace(/"/g,'""')}"`,
l.email, l.phone, l.temperature, `"${(l.repActions||[]).join("; ")}"`,
`"${(l.repNote||"").replace(/"/g,'""')}"`, `"${(l.mktgActions||[]).join("; ")}"`,
`"${(l.notes||"").replace(/"/g,'""')}"`, l.startTime.toISOString(),
l.endTime ? l.endTime.toISOString() : “”, durMin(l.startTime, l.endTime) || “”,
l.staffName, eventName, l.source || “manual”,
]);
const csv = [h, …rows].map(r => r.join(”,”)).join(”\n”);
const blob = new Blob([csv], { type: “text/csv” });
const url = URL.createObjectURL(blob);
const a = document.createElement(“a”); a.href = url;
a.download = `boothspark_${eventName.replace(/\s/g, "_") || "export"}.csv`;
a.click(); URL.revokeObjectURL(url);
};

const totalCount = leads.length;
const hot = leads.filter(l => l.temperature === “hot”).length;
const warm = leads.filter(l => l.temperature === “warm”).length;

const TABS = [
{ id: “capture”, label: “Capture”, icon: “✏️” },
{ id: “import”, label: “Import”, icon: “📥” },
{ id: “dashboard”, label: “Dashboard”, icon: “📊” },
];

return (
<div style={{
minHeight: “100vh”,
background: tab === “dashboard” ? “linear-gradient(165deg, #0d0d1a, #1a1a2e, #16213e)” : “#f5f5f0”,
fontFamily: “‘DM Sans’, sans-serif”, maxWidth: 480, margin: “0 auto”,
transition: “background 0.4s”,
}}>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700;800&family=Outfit:wght@700;800;900&family=JetBrains+Mono:wght@400;600;700;800&display=swap" rel="stylesheet" />

```
  {/* Header */}
  <div style={{ background: "#1a1a2e", padding: "18px 20px 12px", position: "sticky", top: 0, zIndex: 100 }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <div>
        <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: 3, color: "#FF6B35", textTransform: "uppercase" }}>BoothSpark</div>
        <div style={{ fontSize: 16, fontWeight: 800, color: "#fff", fontFamily: "'Outfit', sans-serif", marginTop: 1 }}>
          {eventName || "Lead Capture"}
        </div>
      </div>
      {totalCount > 0 && (
        <div style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 11, fontWeight: 700 }}>
          <span style={{ color: "#E8572A" }}>🔥{hot}</span>
          <span style={{ color: "#FF9F1C" }}>☀️{warm}</span>
          <span style={{ color: "#2EC4B6" }}>💧{totalCount - hot - warm}</span>
          <span style={{ color: "#fff", fontSize: 18, fontFamily: "'Outfit', sans-serif", marginLeft: 4 }}>{totalCount}</span>
        </div>
      )}
    </div>

    {/* Tab bar */}
    <div style={{ display: "flex", gap: 4, marginTop: 12 }}>
      {TABS.map(t => (
        <button key={t.id} onClick={() => setTab(t.id)} style={{
          flex: 1, padding: "9px 0", borderRadius: 8, border: "none",
          background: tab === t.id ? "#FF6B35" : "#ffffff0d",
          color: tab === t.id ? "#fff" : "#ffffff55",
          fontSize: 11, fontWeight: 700, cursor: "pointer", transition: "all 0.2s",
        }}>
          {t.icon} {t.label}
        </button>
      ))}
    </div>
  </div>

  {/* ─── CAPTURE TAB ─── */}
  {tab === "capture" && (
    <div style={{ padding: "14px 16px 110px" }}>
      {totalCount === 0 && !showForm && (
        <div style={{ background: "#fff", borderRadius: 14, padding: "18px 16px", marginBottom: 14, boxShadow: "0 1px 4px #0001" }}>
          <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 10 }}>Quick Setup</div>
          <Input value={eventName} onChange={e => setEventName(e.target.value)} placeholder="Event name" />
          <Input value={staffName} onChange={e => setStaffName(e.target.value)} placeholder="Your name" />
        </div>
      )}

      {showForm && (
        <div style={{ background: "#fff", borderRadius: 16, padding: "18px 16px", marginBottom: 14, boxShadow: "0 4px 20px #0001" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
            <div style={{ fontSize: 15, fontWeight: 800, color: "#1a1a2e", fontFamily: "'Outfit', sans-serif" }}>
              {formStep === 1 ? "Who'd you meet?" : "What happens next?"}
            </div>
            <button onClick={() => { resetForm(); setShowForm(false); }} style={{ background: "none", border: "none", fontSize: 20, color: "#ccc", cursor: "pointer" }}>×</button>
          </div>
          <div style={{ display: "flex", gap: 6, marginBottom: 14 }}>
            {[1, 2].map(s => <div key={s} style={{ height: 3, flex: 1, borderRadius: 2, background: s <= formStep ? "#FF6B35" : "#e8e8e8" }} />)}
          </div>

          {formStep === 1 ? (
            <>
              <Input value={name} onChange={e => setName(e.target.value)} placeholder="Name *" autoComplete="name" />
              <Input value={company} onChange={e => setCompany(e.target.value)} placeholder="Company" autoComplete="organization" />
              <Input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" type="email" autoComplete="email" />
              <Input value={phone} onChange={e => setPhone(e.target.value)} placeholder="Phone" type="tel" autoComplete="tel" />
              <SectionLabel color="#666">Temperature</SectionLabel>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {TEMP_OPTIONS.map(t => <Pill key={t.value} selected={temperature === t.value} color={t.color} onClick={() => setTemperature(t.value)}>{t.label}</Pill>)}
              </div>
              <button onClick={() => setFormStep(2)} disabled={!name.trim()} style={{
                marginTop: 16, width: "100%", padding: "13px", borderRadius: 12, border: "none",
                fontSize: 14, fontWeight: 800, cursor: "pointer",
                background: name.trim() ? "#FF6B35" : "#ddd", color: name.trim() ? "#fff" : "#999",
              }}>Next: Actions →</button>
            </>
          ) : (
            <>
              <SectionLabel color="#9B5DE5">What did you promise?</SectionLabel>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {REP_ACTIONS.map(a => <Pill key={a.value} selected={repActions.includes(a.value)} color="#9B5DE5" onClick={() => toggle(repActions, setRepActions, a.value)}>{a.label}</Pill>)}
              </div>
              {repActions.length > 0 && !repActions.includes("none") && (
                <input value={repNote} onChange={e => setRepNote(e.target.value)} placeholder="Specifics — what exactly?"
                  style={{ width: "100%", padding: "10px 14px", border: "2px solid #9B5DE522", borderRadius: 10, fontSize: 13, marginTop: 8, outline: "none", background: "#9B5DE506", boxSizing: "border-box" }}
                />
              )}
              <SectionLabel color="#1A936F">What should marketing do?</SectionLabel>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {MKTG_ACTIONS.map(a => <Pill key={a.value} selected={mktgActions.includes(a.value)} color="#1A936F" onClick={() => toggle(mktgActions, setMktgActions, a.value)}>{a.label}</Pill>)}
              </div>
              <SectionLabel color="#888">Notes</SectionLabel>
              <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="Context, pain points..." rows={2}
                style={{ width: "100%", padding: "10px 14px", border: "2px solid #e8e8e8", borderRadius: 10, fontSize: 13, resize: "none", outline: "none", background: "#fafafa", boxSizing: "border-box" }}
              />
              <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
                <button onClick={() => setFormStep(1)} style={{ flex: 1, padding: "12px", borderRadius: 12, border: "2px solid #e8e8e8", background: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer", color: "#888" }}>← Back</button>
                <button onClick={saveLead} style={{ flex: 2, padding: "12px", borderRadius: 12, border: "none", background: "#FF6B35", color: "#fff", fontSize: 14, fontWeight: 800, cursor: "pointer" }}>Save & Start Timer</button>
              </div>
            </>
          )}
        </div>
      )}

      {leads.map(l => <LeadCard key={l.id} lead={l} isActive={l.id === activeId} onEnd={() => endConvo(l.id)} />)}

      {totalCount === 0 && !showForm && (
        <div style={{ textAlign: "center", padding: "36px 20px", color: "#bbb" }}>
          <div style={{ fontSize: 32, marginBottom: 6 }}>👋</div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>No leads yet</div>
          <div style={{ fontSize: 11, marginTop: 3 }}>Tap below to start capturing</div>
        </div>
      )}

      {/* Bottom bar */}
      <div style={{
        position: "fixed", bottom: 0, left: "50%", transform: "translateX(-50%)",
        width: "100%", maxWidth: 480, background: "#fff", borderTop: "1px solid #eee",
        padding: "10px 16px", display: "flex", gap: 10, zIndex: 100,
      }}>
        <button onClick={() => { setShowForm(true); setFormStep(1); }} style={{
          flex: 2, padding: "13px", borderRadius: 12, border: "none",
          background: "#FF6B35", color: "#fff", fontSize: 15, fontWeight: 800, cursor: "pointer",
        }}>+ New Lead</button>
        {totalCount > 0 && (
          <button onClick={exportCSV} style={{
            flex: 1, padding: "13px", borderRadius: 12, border: "2px solid #1a1a2e",
            background: "#fff", color: "#1a1a2e", fontSize: 12, fontWeight: 700, cursor: "pointer",
          }}>📥 CSV</button>
        )}
      </div>
    </div>
  )}

  {/* ─── IMPORT TAB ─── */}
  {tab === "import" && (
    <div style={{ padding: "20px 16px 40px" }}>
      {/* CSV Upload */}
      <div style={{ background: "#fff", borderRadius: 16, padding: "24px 18px", marginBottom: 16, boxShadow: "0 1px 4px #0001" }}>
        <div style={{ fontSize: 15, fontWeight: 800, fontFamily: "'Outfit', sans-serif", marginBottom: 4 }}>Upload Badge Scan or Lead List</div>
        <div style={{ fontSize: 12, color: "#888", marginBottom: 16, lineHeight: 1.4 }}>
          CSV export from your badge scanner, lead retrieval app, or spreadsheet. We'll auto-detect name, company, email, and phone columns.
        </div>
        <input ref={fileRef} type="file" accept=".csv,.txt" onChange={handleFile} style={{ display: "none" }} />
        <button onClick={() => fileRef.current?.click()} style={{
          width: "100%", padding: "16px", borderRadius: 12, border: "2px dashed #ddd",
          background: "#fafafa", fontSize: 14, fontWeight: 700, cursor: "pointer",
          color: "#888", transition: "all 0.2s",
        }}>
          📂 Choose CSV File
        </button>
      </div>

      {/* Import Preview */}
      {importPreview && (
        <div style={{ background: "#fff", borderRadius: 16, padding: "20px 18px", marginBottom: 16, boxShadow: "0 1px 4px #0001" }}>
          <div style={{ fontSize: 14, fontWeight: 800, marginBottom: 4, fontFamily: "'Outfit', sans-serif" }}>
            Preview: {importCount} leads found
          </div>
          <div style={{ fontSize: 11, color: "#888", marginBottom: 14 }}>Column mapping (auto-detected):</div>

          {["name", "company", "email", "phone"].map(field => (
            <div key={field} style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: "#1a1a2e", width: 70, textTransform: "capitalize" }}>{field}</span>
              <span style={{ fontSize: 11, color: "#999" }}>→</span>
              <select value={importMapping[field] ?? ""} onChange={e => setImportMapping(p => ({ ...p, [field]: e.target.value === "" ? undefined : Number(e.target.value) }))}
                style={{ flex: 1, padding: "8px 10px", borderRadius: 8, border: "2px solid #e8e8e8", fontSize: 12, background: "#fafafa" }}>
                <option value="">— Skip —</option>
                {importPreview.headers.map((h, i) => <option key={i} value={i}>{h}</option>)}
              </select>
            </div>
          ))}

          {/* Sample rows */}
          <div style={{ marginTop: 12, padding: "10px 12px", background: "#fafafa", borderRadius: 10, fontSize: 11, color: "#666", maxHeight: 120, overflow: "auto" }}>
            {importPreview.rows.slice(0, 3).map((row, i) => (
              <div key={i} style={{ marginBottom: 4 }}>
                {importMapping.name !== undefined && <strong>{row[importMapping.name]}</strong>}
                {importMapping.company !== undefined && <span> · {row[importMapping.company]}</span>}
                {importMapping.email !== undefined && <span> · {row[importMapping.email]}</span>}
              </div>
            ))}
            {importCount > 3 && <div style={{ color: "#bbb" }}>...and {importCount - 3} more</div>}
          </div>

          <button onClick={doImport} style={{
            marginTop: 14, width: "100%", padding: "14px", borderRadius: 12,
            border: "none", background: "#2EC4B6", color: "#fff",
            fontSize: 14, fontWeight: 800, cursor: "pointer",
          }}>
            Import {importCount} Leads
          </button>
          <div style={{ fontSize: 10, color: "#999", textAlign: "center", marginTop: 6 }}>
            Imported leads need temperature + actions tagged on the Capture tab
          </div>
        </div>
      )}

      {/* Business card stub */}
      <div style={{
        background: "#fff", borderRadius: 16, padding: "24px 18px",
        boxShadow: "0 1px 4px #0001", opacity: 0.6,
      }}>
        <div style={{ fontSize: 15, fontWeight: 800, fontFamily: "'Outfit', sans-serif", marginBottom: 4 }}>📷 Scan Business Card</div>
        <div style={{ fontSize: 12, color: "#888", lineHeight: 1.4, marginBottom: 14 }}>
          Take a photo of a business card and auto-fill the lead form. Coming soon in the BoothSpark app.
        </div>
        <button disabled style={{
          width: "100%", padding: "14px", borderRadius: 12, border: "2px dashed #ddd",
          background: "#fafafa", fontSize: 13, fontWeight: 700, color: "#ccc",
        }}>
          📷 Coming Soon
        </button>
      </div>
    </div>
  )}

  {/* ─── DASHBOARD TAB ─── */}
  {tab === "dashboard" && (
    <Dashboard leads={leads} eventName={eventName} costs={costs} setCosts={setCosts} />
  )}
</div>
```

);
}
// JavaScript Document