"use client";

// ============================================================
// Leads — storm-restoration pipeline board.
//   · Hero head : storm banner + headline stats (by status)
//   · Toolbar   : search + status filter tabs
//   · Board     : lead cards (avatar, priority ring, status,
//                 address, phone, source, rep, updated)
//   · Detail    : click a lead → rich popup with Contact,
//                 Property, Job Details, Insurance, Assignment
// Data comes from leads-data.ts (client-side mock).
// ============================================================

import { useMemo, useState, type ReactNode } from "react";
import { Avatar, Btn, Field, Icon, Modal, PageHead, Pill, Segmented, SegTabs, useToast } from "./ui";
import {
  LEADS, TOTAL_LEADS, STATUS_META, PRIORITY_META,
  REPS, LEAD_SOURCES, WORK_TYPES, TRADE_TYPES, CLAIM_STATUSES,
  type Lead, type LeadStatus,
} from "./leads-data";

const STATUS_TABS: { value: "all" | LeadStatus; label: string }[] = [
  { value: "all", label: "All" },
  { value: "new", label: "New" },
  { value: "contacted", label: "Contacted" },
  { value: "appointed", label: "Appointed" },
  { value: "closed", label: "Closed" },
];

export function Leads() {
  const toast = useToast();
  const [query, setQuery] = useState("");
  const [filter, setFilter] = useState<"all" | LeadStatus>("all");
  const [selected, setSelected] = useState<Lead | null>(null);
  const [newOpen, setNewOpen] = useState(false);

  const countByStatus = useMemo(() => {
    const m: Record<string, number> = {};
    for (const l of LEADS) m[l.status] = (m[l.status] ?? 0) + 1;
    return m;
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return LEADS.filter((l) => {
      const matchStatus = filter === "all" || l.status === filter;
      const hay = `${l.name} ${l.property.address} ${l.property.city} ${l.job.source} ${l.job.canvasser}`.toLowerCase();
      return matchStatus && (!q || hay.includes(q));
    });
  }, [query, filter]);

  return (
    <div className="view leads">
      <PageHead
        eyebrow="Sales"
        title="Leads"
        subtitle={`${TOTAL_LEADS} total leads · Plano hail zone · storm 2026-04-28`}
        icon="leads"
        actions={<Btn icon="plus" onClick={() => setNewOpen(true)}>New Lead</Btn>}
      />

      {/* ---- stat strip ---------------------------------------- */}
      <div className="leads-stats">
        <StatCard label="Total leads" value={TOTAL_LEADS} icon="leads" tone="orange" />
        <StatCard label="New" value={countByStatus.new ?? 0} icon="star" tone="blue" />
        <StatCard label="Contacted" value={countByStatus.contacted ?? 0} icon="phone" tone="orange" />
        <StatCard label="Appointed" value={countByStatus.appointed ?? 0} icon="clock" tone="purple" />
        <StatCard label="Closed" value={countByStatus.closed ?? 0} icon="check-circle" tone="green" />
      </div>

      {/* ---- toolbar ------------------------------------------- */}
      <div className="leads-toolbar">
        <div className="leads-search">
          <Icon name="search" size={16} />
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search by name, address, source…"
            aria-label="Search leads"
          />
          {query && <button className="leads-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
        </div>
        <div className="leads-tabs" role="tablist">
          {STATUS_TABS.map((t) => (
            <button
              key={t.value}
              role="tab"
              aria-selected={filter === t.value}
              className={`leads-tab ${filter === t.value ? "active" : ""}`}
              onClick={() => setFilter(t.value)}
            >
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* ---- board --------------------------------------------- */}
      {filtered.length === 0 ? (
        <div className="card leads-empty">
          <Icon name="search" size={30} />
          <h3>No leads match</h3>
          <p>Try a different search or clear the status filter.</p>
        </div>
      ) : (
        <div className="leads-grid">
          {filtered.map((l) => (
            <LeadCard key={l.id} lead={l} onOpen={() => setSelected(l)} />
          ))}
        </div>
      )}

      <LeadDetail lead={selected} onClose={() => setSelected(null)} />
      <NewLead open={newOpen} onClose={() => setNewOpen(false)} />
    </div>
  );
}

/* ---------------------------------------------------------- */
/* Stat card                                                   */
/* ---------------------------------------------------------- */

function StatCard({ label, value, icon, tone }: { label: string; value: number; icon: string; tone: string }) {
  return (
    <div className={`leads-stat tone-${tone}`}>
      <span className="leads-stat-ic"><Icon name={icon} size={17} /></span>
      <div className="leads-stat-body">
        <div className="leads-stat-val">{value}</div>
        <div className="leads-stat-lbl">{label}</div>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------- */
/* Lead card                                                   */
/* ---------------------------------------------------------- */

function LeadCard({ lead, onOpen }: { lead: Lead; onOpen: () => void }) {
  const status = STATUS_META[lead.status];
  const priority = PRIORITY_META[lead.priority];
  const primaryPhone = lead.phones.find((p) => p.primary) ?? lead.phones[0];

  return (
    <button className="lead-card" onClick={onOpen}>
      <div className="lead-card-top">
        <span className={`lead-ava prio-${lead.priority}`}>
          <Avatar initials={lead.initials} gradient={lead.gradient} size={46} />
        </span>
        <div className="lead-card-id">
          <div className="lead-card-name">{lead.name}</div>
          <div className="lead-card-sub"><span className="lead-code">{lead.id}</span> · <Icon name="storm" size={12} /> {lead.tag}</div>
        </div>
        <Pill tone={priority.tone}><Icon name="alert" size={11} /> {priority.label}</Pill>
      </div>

      <div className="lead-card-row"><Icon name="pin" size={14} /><span>{lead.property.address}, {lead.property.city}, {lead.property.state}</span></div>
      <div className="lead-card-row"><Icon name="phone" size={14} /><span>{primaryPhone?.number}</span></div>

      <div className="lead-card-foot">
        <Pill tone={status.tone}>{status.label}</Pill>
        <span className="lead-source"><Icon name="pin" size={12} /> {lead.job.source}</span>
        <span className="lead-card-spacer" />
        <span className="lead-rep" title={`Canvasser: ${lead.job.canvasser}`}>{lead.job.canvasser}</span>
        <span className="lead-updated">{lead.updated}</span>
      </div>
    </button>
  );
}

/* ---------------------------------------------------------- */
/* Lead detail popup                                           */
/* ---------------------------------------------------------- */

function LeadDetail({ lead, onClose }: { lead: Lead | null; onClose: () => void }) {
  if (!lead) return null;
  const status = STATUS_META[lead.status];
  const priority = PRIORITY_META[lead.priority];

  return (
    <Modal
      open={!!lead}
      onClose={onClose}
      size="lg"
      title={lead.name}
      subtitle={`${lead.id} · ${lead.tag}`}
      icon="leads"
      footer={
        <>
          <Btn variant="ghost" icon="phone">Call</Btn>
          <Btn variant="outline" icon="mail">Email</Btn>
          <Btn icon="check-circle">Update Status</Btn>
        </>
      }
    >
      <div className="lead-detail">
        {/* identity strip */}
        <div className="ld-identity">
          <Avatar initials={lead.initials} gradient={lead.gradient} size={54} />
          <div className="ld-identity-body">
            <div className="ld-identity-name">{lead.name}</div>
            <div className="ld-identity-pills">
              <Pill tone={status.tone}>{status.label}</Pill>
              <Pill tone={priority.tone}><Icon name="alert" size={11} /> {priority.label}</Pill>
            </div>
          </div>
        </div>

        {/* storm banner */}
        <div className="ld-storm">
          <span className="ld-storm-ic"><Icon name="storm" size={18} /></span>
          <div>
            <div className="ld-storm-zone">{lead.storm.zone}</div>
            <div className="ld-storm-meta">{lead.storm.date} · {lead.storm.detail}</div>
          </div>
        </div>

        <div className="ld-grid">
          {/* Contact */}
          <Section title="Contact" icon="user">
            <div className="ld-sublabel">Phone Numbers</div>
            {lead.phones.map((p, i) => (
              <div className="ld-contact-row" key={i}>
                <Icon name="phone" size={14} />
                <span className="ld-contact-val">{p.number}</span>
                <span className="ld-contact-tag">{p.type}</span>
                {p.primary && <Pill tone="green">Primary</Pill>}
              </div>
            ))}
            <div className="ld-sublabel">Email Addresses</div>
            {lead.emails.map((e, i) => (
              <div className="ld-contact-row" key={i}>
                <Icon name="mail" size={14} />
                <span className="ld-contact-val">{e.address}</span>
                {e.primary && <Pill tone="green">Primary</Pill>}
              </div>
            ))}
          </Section>

          {/* Property */}
          <Section title="Property" icon="owners">
            <Dl label="Address" value={lead.property.address} />
            <Dl label="City" value={lead.property.city} />
            <Dl label="State" value={lead.property.state} />
            <Dl label="ZIP" value={lead.property.zip} />
            <Dl label="Property Type" value={lead.property.type} />
          </Section>

          {/* Job Details */}
          <Section title="Job Details" icon="projects">
            <Dl label="Lead Source" value={lead.job.source} />
            <Dl label="Lead Type" value={lead.job.leadType} />
            <Dl label="Work Type" value={lead.job.workType} />
            <Dl label="Trade Type" value={lead.job.tradeType} />
            <Dl label="Urgency" value={lead.job.urgency} />
            <Dl label="Canvasser" value={lead.job.canvasser} />
            <div className="ld-notes">
              <div className="ld-sublabel">Field Notes</div>
              <p>{lead.job.notes}</p>
            </div>
          </Section>

          {/* Insurance */}
          <Section title="Insurance" icon="shield">
            <Dl label="Insurance Company" value={lead.insurance.company} />
            <Dl label="Claim Status" value={lead.insurance.claimStatus} />
            <Dl label="Claim Number" value={lead.insurance.claimNumber} />
            <Dl label="Policy Number" value={lead.insurance.policyNumber} />
            <Dl label="Adjuster Name" value={lead.insurance.adjusterName} />
            <Dl label="Adjuster Phone" value={lead.insurance.adjusterPhone} />
          </Section>

          {/* Assignment */}
          <Section title="Assignment" icon="team" wide>
            <div className="ld-assign">
              <Dl label="Assigned To" value={lead.assignment.assignedTo} />
              <Dl label="Priority" value={lead.assignment.priority} />
              <Dl label="Follow-Up Date" value={lead.assignment.followUp} />
              <Dl label="Created By" value={lead.assignment.createdBy} />
              <Dl label="Created At" value={lead.assignment.createdAt} />
            </div>
          </Section>
        </div>
      </div>
    </Modal>
  );
}

function Section({ title, icon, children, wide }: { title: string; icon: string; children: ReactNode; wide?: boolean }) {
  return (
    <div className={`ld-section ${wide ? "wide" : ""}`}>
      <div className="ld-section-head"><Icon name={icon} size={15} /> {title}</div>
      <div className="ld-section-body">{children}</div>
    </div>
  );
}

function Dl({ label, value }: { label: string; value: string }) {
  return (
    <div className="ld-dl">
      <span className="ld-dl-k">{label}</span>
      <span className="ld-dl-v">{value}</span>
    </div>
  );
}

/* ---------------------------------------------------------- */
/* New Lead — Quick / Full Form intake                         */
/* ---------------------------------------------------------- */

type Priority = "Low" | "Medium" | "High";
type Urgency = "Standard" | "High" | "Emergency";
type PhoneRow = { number: string; type: string };
type EmailRow = { address: string };

const FULL_STEPS = [
  { value: "contact", label: "Contact", icon: "user" },
  { value: "property", label: "Property", icon: "owners" },
  { value: "job", label: "Job Details", icon: "projects" },
  { value: "insurance", label: "Insurance", icon: "shield" },
  { value: "assignment", label: "Assignment", icon: "team" },
];

const LEAD_TYPE_OPTS = ["Residential", "Commercial", "Multi-Family"];
const PROPERTY_TYPE_OPTS = ["Residential", "Commercial", "Multi-Family", "Industrial"];

const BLANK = {
  firstName: "", lastName: "",
  phones: [{ number: "", type: "Mobile" }] as PhoneRow[],
  emails: [] as EmailRow[],
  address: "", city: "", state: "TX", zip: "", propertyType: "",
  photos: [] as string[],
  source: "", referralNote: "", canvasser: "", leadType: "", workType: "", tradeType: "", urgency: "Standard" as Urgency, notes: "",
  insCompany: "", claimNumber: "", claimStatus: "", adjusterName: "", adjusterPhone: "", policyNumber: "",
  assignRep: "", priority: "Medium" as Priority, followUp: "",
};

function NewLead({ open, onClose }: { open: boolean; onClose: () => void }) {
  const toast = useToast();
  const [mode, setMode] = useState<"quick" | "full">("quick");
  const [section, setSection] = useState("contact");
  const [f, setF] = useState({ ...BLANK });

  const set = (k: string) => (e: { target: { value: string } }) =>
    setF((s) => ({ ...s, [k]: e.target.value }) as typeof BLANK);

  // multi-value handlers
  const addPhone = () => setF((s) => ({ ...s, phones: [...s.phones, { number: "", type: "Mobile" }] }));
  const setPhone = (i: number, key: "number" | "type", v: string) => setF((s) => ({ ...s, phones: s.phones.map((p, j) => (j === i ? { ...p, [key]: v } : p)) }));
  const removePhone = (i: number) => setF((s) => ({ ...s, phones: s.phones.filter((_, j) => j !== i) }));
  const addEmail = () => setF((s) => ({ ...s, emails: [...s.emails, { address: "" }] }));
  const setEmail = (i: number, v: string) => setF((s) => ({ ...s, emails: s.emails.map((e, j) => (j === i ? { address: v } : e)) }));
  const removeEmail = (i: number) => setF((s) => ({ ...s, emails: s.emails.filter((_, j) => j !== i) }));
  const addPhoto = () => setF((s) => ({ ...s, photos: [...s.photos, `Photo ${s.photos.length + 1}`] }));

  function reset() { setF({ ...BLANK, phones: [{ number: "", type: "Mobile" }], emails: [], photos: [] }); setMode("quick"); setSection("contact"); }
  function close() { reset(); onClose(); }

  function submit() {
    const name = `${f.firstName} ${f.lastName}`.trim();
    if (!name) { toast.push({ tone: "error", title: "Name required", desc: "Enter the homeowner's first or last name." }); return; }
    toast.push({ tone: "success", title: "Lead created", desc: `${name} added to the Plano pipeline.` });
    close();
  }

  const repOptions = [{ id: "", initials: "—", name: "Unassigned" }, ...REPS];

  const stepIdx = FULL_STEPS.findIndex((s) => s.value === section);
  const isFirstStep = stepIdx <= 0;
  const isLastStep = stepIdx === FULL_STEPS.length - 1;
  const goNext = () => { if (!isLastStep) setSection(FULL_STEPS[stepIdx + 1].value); };
  const goBack = () => { if (!isFirstStep) setSection(FULL_STEPS[stepIdx - 1].value); };

  return (
    <Modal
      open={open}
      onClose={close}
      size="lg"
      title="New Lead"
      subtitle="Full lead profile with insurance and assignment details."
      icon="plus"
      footer={
        mode === "full" ? (
          <>
            <Btn variant="ghost" onClick={close}>Cancel</Btn>
            {!isFirstStep && <Btn variant="ghost" onClick={goBack}>Back</Btn>}
            {isLastStep
              ? <Btn icon="check" onClick={submit}>Create Lead</Btn>
              : <Btn icon="arrow" onClick={goNext}>Next</Btn>}
          </>
        ) : (
          <>
            <Btn variant="ghost" onClick={close}>Cancel</Btn>
            <Btn icon="check" onClick={submit}>Create Lead</Btn>
          </>
        )
      }
    >
      <div className="nl-form">
        <Segmented
          value={mode}
          onChange={(v) => setMode(v as "quick" | "full")}
          options={[{ value: "quick", label: "Quick", icon: "star" }, { value: "full", label: "Full Form", icon: "edit" }]}
        />

        {mode === "quick" ? (
          <div className="nl-grid">
            <Field label="First name" required><input className="ds-input" value={f.firstName} onChange={set("firstName")} placeholder="John" /></Field>
            <Field label="Last name"><input className="ds-input" value={f.lastName} onChange={set("lastName")} placeholder="Smith" /></Field>
            <Field label="Phone"><input className="ds-input" value={f.phones[0]?.number ?? ""} onChange={(e) => setPhone(0, "number", e.target.value)} placeholder="(555) 000-0000" /></Field>
            <div className="nl-full"><Field label="Street address"><input className="ds-input" value={f.address} onChange={set("address")} placeholder="123 Main St" /></Field></div>
            <Field label="City"><input className="ds-input" value={f.city} onChange={set("city")} placeholder="Plano" /></Field>
            <Field label="State"><input className="ds-input" value={f.state} onChange={set("state")} /></Field>
            <Field label="ZIP"><input className="ds-input" value={f.zip} onChange={set("zip")} placeholder="75023" /></Field>
            <Field label="Lead source"><Select value={f.source} onChange={set("source")} options={LEAD_SOURCES} placeholder="How did you find this lead?" /></Field>
            {f.source === "Referral" && (
              <div className="nl-full"><Field label="Referral note"><textarea className="ds-textarea" rows={3} value={f.referralNote} onChange={set("referralNote")} placeholder="Who referred this lead? Any details…" /></Field></div>
            )}
            {f.source === "Door Knock" && (
              <div className="nl-full"><Field label="Canvasser"><CanvasserSearch value={f.canvasser} onChange={(v) => setF((s) => ({ ...s, canvasser: v }))} options={REPS} /></Field></div>
            )}
            <div className="nl-full"><PriorityPicker value={f.priority} onChange={(p) => setF((s) => ({ ...s, priority: p }))} /></div>
            <Field label="Follow-up date"><input className="ds-input" type="date" value={f.followUp} onChange={set("followUp")} /></Field>
          </div>
        ) : (
          <>
            <SegTabs
              value={section}
              onChange={setSection}
              tabs={FULL_STEPS}
            />

            {section === "contact" && (
              <div className="nl-grid">
                <Field label="First Name" required><input className="ds-input" value={f.firstName} onChange={set("firstName")} placeholder="John" /></Field>
                <Field label="Last Name"><input className="ds-input" value={f.lastName} onChange={set("lastName")} placeholder="Smith" /></Field>

                <div className="nl-full">
                  <div className="ds-field-lbl">Phone Numbers</div>
                  {f.phones.map((p, i) => (
                    <div className="nl-multirow" key={i}>
                      <input className="ds-input" value={p.number} onChange={(e) => setPhone(i, "number", e.target.value)} placeholder="(555) 000-0000" />
                      <select className="ds-select nl-typesel" value={p.type} onChange={(e) => setPhone(i, "type", e.target.value)}>
                        {["Mobile", "Home", "Work"].map((t) => <option key={t} value={t}>{t}</option>)}
                      </select>
                      {f.phones.length > 1 && <button type="button" className="nl-rowx" aria-label="Remove phone" onClick={() => removePhone(i)}><Icon name="trash" size={15} /></button>}
                    </div>
                  ))}
                  <button type="button" className="nl-add" onClick={addPhone}><Icon name="plus" size={14} /> Add Phone</button>
                </div>

                <div className="nl-full">
                  <div className="ds-field-lbl">Email Addresses</div>
                  {f.emails.length === 0 && <div className="nl-empty">No emails added yet.</div>}
                  {f.emails.map((em, i) => (
                    <div className="nl-multirow" key={i}>
                      <input className="ds-input" type="email" value={em.address} onChange={(e) => setEmail(i, e.target.value)} placeholder="name@email.com" />
                      <button type="button" className="nl-rowx" aria-label="Remove email" onClick={() => removeEmail(i)}><Icon name="trash" size={15} /></button>
                    </div>
                  ))}
                  <button type="button" className="nl-add" onClick={addEmail}><Icon name="plus" size={14} /> Add Email</button>
                </div>
              </div>
            )}

            {section === "property" && (
              <div className="nl-grid">
                <div className="nl-full"><Field label="Street Address"><input className="ds-input" value={f.address} onChange={set("address")} placeholder="123 Main St" /></Field></div>
                <Field label="City"><input className="ds-input" value={f.city} onChange={set("city")} placeholder="Plano" /></Field>
                <Field label="State"><input className="ds-input" value={f.state} onChange={set("state")} placeholder="TX" /></Field>
                <Field label="ZIP"><input className="ds-input" value={f.zip} onChange={set("zip")} placeholder="75023" /></Field>
                <Field label="Property Type"><Select value={f.propertyType} onChange={set("propertyType")} options={PROPERTY_TYPE_OPTS} placeholder="Residential, Commercial…" /></Field>
                <div className="nl-full">
                  <div className="ds-field-lbl">Site Photos</div>
                  <button type="button" className="nl-photos" onClick={addPhoto}>
                    <Icon name="camera" size={22} />
                    <span className="nl-photos-t">Tap to add photos</span>
                    <span className="nl-photos-s">Camera · Gallery · Multiple allowed</span>
                  </button>
                  {f.photos.length > 0 && (
                    <div className="nl-photo-chips">
                      {f.photos.map((p, i) => <span key={i} className="nl-photo-chip"><Icon name="check" size={12} /> {p}</span>)}
                    </div>
                  )}
                </div>
              </div>
            )}

            {section === "job" && (
              <div className="nl-grid">
                <Field label="Lead Source"><Select value={f.source} onChange={set("source")} options={LEAD_SOURCES} placeholder="How did you find this lead?" /></Field>
                <Field label="Lead Type"><Select value={f.leadType} onChange={set("leadType")} options={LEAD_TYPE_OPTS} placeholder="Residential, Commercial…" /></Field>
                <Field label="Work Type"><Select value={f.workType} onChange={set("workType")} options={WORK_TYPES} placeholder="Roof Replacement, Repair…" /></Field>
                <Field label="Trade Type"><Select value={f.tradeType} onChange={set("tradeType")} options={TRADE_TYPES} placeholder="Roofing, Gutter, Siding…" /></Field>
                <div className="nl-full"><UrgencyPicker value={f.urgency} onChange={(u) => setF((s) => ({ ...s, urgency: u }))} /></div>
                <div className="nl-full"><Field label="Notes"><textarea className="ds-textarea" rows={3} value={f.notes} onChange={set("notes")} placeholder="First impression, visible damage, special circumstances…" /></Field></div>
              </div>
            )}

            {section === "insurance" && (
              <div className="nl-grid">
                <div className="nl-full"><Field label="Insurance Company"><input className="ds-input" value={f.insCompany} onChange={set("insCompany")} placeholder="State Farm" /></Field></div>
                <Field label="Claim Number"><input className="ds-input" value={f.claimNumber} onChange={set("claimNumber")} placeholder="e.g. CLM-2026-00482" /></Field>
                <Field label="Claim Status"><Select value={f.claimStatus} onChange={set("claimStatus")} options={CLAIM_STATUSES} placeholder="Select status…" /></Field>
                <Field label="Adjuster Name"><input className="ds-input" value={f.adjusterName} onChange={set("adjusterName")} placeholder="Full name" /></Field>
                <Field label="Adjuster Phone"><input className="ds-input" value={f.adjusterPhone} onChange={set("adjusterPhone")} placeholder="(555) 000-0000" /></Field>
                <div className="nl-full"><Field label="Policy Number"><input className="ds-input" value={f.policyNumber} onChange={set("policyNumber")} placeholder="e.g. POL-7734892-A" /></Field></div>
              </div>
            )}

            {section === "assignment" && (
              <div className="nl-grid">
                <div className="nl-full"><Field label="Assign Rep"><RepSelect value={f.assignRep} onChange={set("assignRep")} options={repOptions} /></Field></div>
                <div className="nl-full"><PriorityPicker value={f.priority} onChange={(p) => setF((s) => ({ ...s, priority: p }))} /></div>
                <Field label="Follow-up Date"><input className="ds-input" type="date" value={f.followUp} onChange={set("followUp")} /></Field>
              </div>
            )}
          </>
        )}
      </div>
    </Modal>
  );
}

function Select({ value, onChange, options, placeholder }: { value: string; onChange: (e: { target: { value: string } }) => void; options: string[]; placeholder?: string }) {
  return (
    <select className={`ds-select ${!value && placeholder ? "is-placeholder" : ""}`} value={value} onChange={onChange}>
      {placeholder && <option value="" disabled>{placeholder}</option>}
      {options.map((o) => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

function RepSelect({ value, onChange, options }: { value: string; onChange: (e: { target: { value: string } }) => void; options: { id: string; initials: string; name: string }[] }) {
  return (
    <select className="ds-select" value={value} onChange={onChange}>
      {options.map((r) => <option key={r.id || "none"} value={r.id}>{r.id ? `${r.name} · ${r.id}` : "— Unassigned"}</option>)}
    </select>
  );
}

function CanvasserSearch({ value, onChange, options }: { value: string; onChange: (v: string) => void; options: { id: string; initials: string; name: string; email: string }[] }) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const selected = options.find((o) => o.id === value);
  const matches = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return options;
    return options.filter((o) => o.name.toLowerCase().includes(q) || o.email.toLowerCase().includes(q));
  }, [query, options]);

  if (selected) {
    return (
      <div className="nl-canvasser-chip">
        <Avatar initials={selected.initials} size={28} />
        <span className="nl-canvasser-name">{selected.name}</span>
        <span className="nl-canvasser-email">{selected.email}</span>
        <button type="button" className="nl-canvasser-clear" onClick={() => { onChange(""); setQuery(""); }} aria-label="Clear canvasser"><Icon name="x" size={14} /></button>
      </div>
    );
  }

  return (
    <div className="nl-canvasser">
      <input
        className="ds-input"
        value={query}
        onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)}
        onBlur={() => setTimeout(() => setOpen(false), 150)}
        placeholder="Search canvasser by name or email"
      />
      {open && matches.length > 0 && (
        <div className="nl-canvasser-menu">
          {matches.map((o) => (
            <button key={o.id} type="button" className="nl-canvasser-opt" onMouseDown={(e) => { e.preventDefault(); onChange(o.id); setQuery(""); setOpen(false); }}>
              <Avatar initials={o.initials} size={26} />
              <span className="nl-canvasser-name">{o.name}</span>
              <span className="nl-canvasser-email">{o.email}</span>
            </button>
          ))}
        </div>
      )}
      {open && matches.length === 0 && (
        <div className="nl-canvasser-menu"><div className="nl-canvasser-empty">No canvasser found</div></div>
      )}
    </div>
  );
}

function PriorityPicker({ value, onChange }: { value: Priority; onChange: (p: Priority) => void }) {
  return (
    <div className="ds-field">
      <span className="ds-field-lbl">Priority</span>
      <div className="nl-prio">
        {(["Low", "Medium", "High"] as Priority[]).map((p) => (
          <button key={p} type="button" className={`nl-prio-btn ${value === p ? `active ${p.toLowerCase()}` : ""}`} onClick={() => onChange(p)}>{p}</button>
        ))}
      </div>
    </div>
  );
}

function UrgencyPicker({ value, onChange }: { value: Urgency; onChange: (u: Urgency) => void }) {
  return (
    <div className="ds-field">
      <span className="ds-field-lbl">Urgency</span>
      <div className="nl-prio">
        {(["Standard", "High", "Emergency"] as Urgency[]).map((u) => (
          <button key={u} type="button" className={`nl-prio-btn urg ${value === u ? `active ${u.toLowerCase()}` : ""}`} onClick={() => onChange(u)}>{u}</button>
        ))}
      </div>
    </div>
  );
}
