/* Forms.jsx — route-driven modals: add/edit Property, Contact, Task, Page,
   Post, Follow-up, plus the new-lead conversion modal and routed wrappers for
   the Note editor and property Contact card. Each form mutates window.PT_DATA,
   bumps the store, fires a toast, and pops itself off the history stack.
   Field model mirrors the legacy schema (see docs/PropTrackr-Functional-Specification.md). */
const { useState } = React;

const US_STATES = ["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY","DC"];
const PROPERTY_TYPES = ["Single Family","Duplex","Townhouse","Condo","Multi-Family","Mobile Home","Commercial","Land"];
const STATUS_OPTS = [["lead","Lead"],["active","Active"],["pending","Pending"],["closing","Closing"],["closed","Closed"],["dead","Dead"]];
const MOTIVATION_OPTS = ["High","Medium","Low","—"];
const DEFAULT_THUMB = "https://images.unsplash.com/photo-1570129477492-45c003edd2be?w=240&q=70&auto=format&fit=crop";

function nextPropId() {
  const nums = window.PT_DATA.properties.map((p) => parseInt(String(p.id).replace(/\D/g, ""), 10)).filter((n) => !isNaN(n));
  return "PT-" + ((nums.length ? Math.max(...nums) : 10000) + 1);
}

/* ---------- Reusable modal shell ---------- */
function Modal({ title, subtitle, icon, iconTone = "brand", onClose, footer, children, width = 600 }) {
  const tone = {
    brand: ["var(--harbor-50)", "var(--harbor-600)"], action: ["var(--ember-50)", "var(--ember-600)"],
    success: ["var(--success-soft)", "var(--success-text)"], info: ["var(--info-soft)", "var(--info-text)"],
  }[iconTone] || ["var(--harbor-50)", "var(--harbor-600)"];
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: "var(--z-modal)", background: "rgba(17,36,44,0.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, backdropFilter: "blur(1.5px)" }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" style={{ width: "100%", maxWidth: width, maxHeight: "92vh", display: "flex", flexDirection: "column", background: "var(--surface-card)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)", overflow: "hidden", animation: "ptdialog var(--dur-base) var(--ease-out)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "18px 22px 14px", borderBottom: "1px solid var(--border-subtle)", flex: "none" }}>
          {icon && <span style={{ width: 38, height: 38, borderRadius: "var(--radius-lg)", background: tone[0], color: tone[1], display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={icon} size={19} /></span>}
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2 style={{ fontSize: "var(--text-lg)", fontWeight: 700, color: "var(--text-strong)" }}>{title}</h2>
            {subtitle && <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{subtitle}</div>}
          </div>
          <IconButton icon="x" label="Close" onClick={onClose} />
        </div>
        <div style={{ padding: 22, overflow: "auto", flex: 1 }}>{children}</div>
        {footer && <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "14px 22px", background: "var(--surface-sunken)", borderTop: "1px solid var(--border-subtle)", flex: "none" }}>{footer}</div>}
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", color: "var(--text-subtle)", marginBottom: 10 }}>{title}</div>
      {children}
    </div>
  );
}
function Grid({ cols = 2, children }) {
  return <div className={"pt-grid pt-grid-" + cols}>{children}</div>;
}
function StateSelect({ value, onChange }) {
  return <Select value={value} onChange={onChange}><option value="">—</option>{US_STATES.map((s) => <option key={s} value={s}>{s}</option>)}</Select>;
}

/* ============================================================
   PROPERTY — add / edit (7 sections from the legacy schema)
   ============================================================ */
function PropertyForm({ property }) {
  const editing = !!property;
  const D = window.PT_DATA;
  const dealTypes = (D.customTypes && D.customTypes["Deal types"]) || ["Wholesale", "Fix & Flip", "Buy & Hold"];
  const [f, setF] = useState(() => ({
    address: property?.address || "", address2: "", city: property?.city || "", state: property?.state || "",
    zip: property?.zip || "", county: property?.county || "", mls: property?.mls || "",
    type: property?.type || "Single Family", deal: property?.deal || dealTypes[0], status: property?.status || "lead",
    source: property?.source || "Webform", motivation: property?.motivation || "Medium",
    beds: property?.beds ?? "", baths: property?.baths ?? "", sqft: property?.sqft ?? "", lot: property?.lot || "",
    year: property?.year ?? "", garage: property?.garage || "Attached", occupancy: property?.occupancy || "Owner-Occupied",
    ask: property?.ask ?? "", offer: property?.offer ?? "", arv: property?.arv ?? "", bpo: property?.bpo ?? "",
    loan: property?.loan ?? "", lowest: property?.lowest ?? "",
    foreclosure: property?.foreclosure || "", auction: property?.auction || "", sellBy: property?.sellBy || "",
    published: property?.published ?? true, hidePublic: property?.hidePublic ?? false,
    assignee: property?.assignee || D.user.name,
  }));
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const num = (v) => (v === "" || v == null ? 0 : parseInt(v, 10) || 0);
  const base = "/properties" + (editing ? "/" + property.id : "");

  function save() {
    if (editing) {
      Object.assign(property, {
        address: f.address, city: f.city, state: f.state, zip: f.zip, county: f.county, mls: f.mls,
        type: f.type, deal: f.deal, status: f.status, source: f.source, motivation: f.motivation,
        beds: num(f.beds), baths: num(f.baths), sqft: num(f.sqft), lot: f.lot, year: num(f.year),
        garage: f.garage, occupancy: f.occupancy, ask: num(f.ask), offer: num(f.offer), arv: num(f.arv),
        bpo: num(f.bpo), loan: num(f.loan), lowest: num(f.lowest),
        foreclosure: f.foreclosure, auction: f.auction, sellBy: f.sellBy, published: f.published, hidePublic: f.hidePublic, assignee: f.assignee,
      });
      PTStore.bump();
      pushToast({ tone: "success", title: "Property updated", body: f.address + " was saved." });
      closeOverlay(base);
    } else {
      const id = nextPropId();
      const p = {
        id, thumb: DEFAULT_THUMB, address: f.address, city: f.city, state: f.state, zip: f.zip, county: f.county,
        mls: f.mls, status: f.status, type: f.type, deal: f.deal, source: f.source, motivation: f.motivation,
        ask: num(f.ask), offer: num(f.offer), arv: num(f.arv), bpo: num(f.bpo), loan: num(f.loan), lowest: num(f.lowest),
        beds: num(f.beds), baths: num(f.baths), sqft: num(f.sqft), year: num(f.year), lot: f.lot || "—",
        garage: f.garage, occupancy: f.occupancy, published: f.published, hidePublic: f.hidePublic, assignee: f.assignee,
        followDate: "—", overdue: false, contacts: [], notes: [],
        lat: 40.0 + (Math.random() - 0.5), lng: -82.9 + (Math.random() - 0.5),
      };
      D.properties.unshift(p);
      PTStore.bump();
      pushToast({ tone: "success", title: "Property created", body: f.address + " was added to your deals." });
      navigate("/properties/" + id);
    }
  }

  return (
    <Modal width={720} icon={editing ? "pencil" : "building-2"} title={editing ? "Edit property" : "Add property"}
      subtitle={editing ? property.id : "Create a new deal"} onClose={() => closeOverlay(base)}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay(base)}>Cancel</Button>
        <Button variant="primary" icon="check" onClick={save} disabled={!f.address}>{editing ? "Save changes" : "Create property"}</Button>
      </>}>
      <Section title="Location & identification">
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Field label="Address" required><Input icon="map-pin" placeholder="412 Oak Street" value={f.address} onChange={set("address")} /></Field>
          <Grid cols={3}>
            <Field label="City"><Input value={f.city} onChange={set("city")} /></Field>
            <Field label="State"><StateSelect value={f.state} onChange={set("state")} /></Field>
            <Field label="ZIP"><Input value={f.zip} onChange={set("zip")} /></Field>
          </Grid>
          <Grid cols={2}>
            <Field label="County"><Input value={f.county} onChange={set("county")} /></Field>
            <Field label="MLS #"><Input placeholder="optional" value={f.mls} onChange={set("mls")} /></Field>
          </Grid>
        </div>
      </Section>

      <Section title="Classification">
        <Grid cols={2}>
          <Field label="Property type"><Select value={f.type} onChange={set("type")}>{PROPERTY_TYPES.map((t) => <option key={t}>{t}</option>)}</Select></Field>
          <Field label="Deal type"><Select value={f.deal} onChange={set("deal")}>{dealTypes.map((t) => <option key={t}>{t}</option>)}</Select></Field>
          <Field label="Status"><Select value={f.status} onChange={set("status")}>{STATUS_OPTS.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</Select></Field>
          <Field label="Motivation"><Select value={f.motivation} onChange={set("motivation")}>{MOTIVATION_OPTS.map((m) => <option key={m}>{m}</option>)}</Select></Field>
        </Grid>
      </Section>

      <Section title="Physical attributes">
        <Grid cols={3}>
          <Field label="Beds"><Input type="number" value={f.beds} onChange={set("beds")} /></Field>
          <Field label="Baths"><Input type="number" value={f.baths} onChange={set("baths")} /></Field>
          <Field label="Sq ft"><Input type="number" value={f.sqft} onChange={set("sqft")} /></Field>
          <Field label="Year built"><Input type="number" value={f.year} onChange={set("year")} /></Field>
          <Field label="Lot size"><Input placeholder="0.18 ac" value={f.lot} onChange={set("lot")} /></Field>
          <Field label="Occupancy"><Select value={f.occupancy} onChange={set("occupancy")}><option>Owner-Occupied</option><option>Rental</option><option>Vacant</option></Select></Field>
        </Grid>
      </Section>

      <Section title="Valuations & pricing">
        <Grid cols={3}>
          <Field label="Asking ($)"><Input type="number" value={f.ask} onChange={set("ask")} /></Field>
          <Field label="Our offer ($)"><Input type="number" value={f.offer} onChange={set("offer")} /></Field>
          <Field label="ARV ($)"><Input type="number" value={f.arv} onChange={set("arv")} /></Field>
          <Field label="BPO / FMV ($)"><Input type="number" value={f.bpo} onChange={set("bpo")} /></Field>
          <Field label="Loan balance ($)"><Input type="number" value={f.loan} onChange={set("loan")} /></Field>
          <Field label="Lowest accept. ($)"><Input type="number" value={f.lowest} onChange={set("lowest")} /></Field>
        </Grid>
      </Section>

      <Section title="Timing & urgency">
        <Grid cols={3}>
          <Field label="Foreclosure date"><Input type="date" value={f.foreclosure} onChange={set("foreclosure")} /></Field>
          <Field label="Auction date"><Input type="date" value={f.auction} onChange={set("auction")} /></Field>
          <Field label="Sell-by date"><Input type="date" value={f.sellBy} onChange={set("sellBy")} /></Field>
        </Grid>
      </Section>

      <Section title="Publishing & team">
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ display: "flex", gap: 24, flexWrap: "wrap" }}>
            <Toggle checked={f.published} onChange={(v) => setF((s) => ({ ...s, published: v }))} label="Published to PropMapr" />
            <Toggle checked={f.hidePublic} onChange={(v) => setF((s) => ({ ...s, hidePublic: v }))} label="Hide from public listings" />
          </div>
          <Field label="Assigned to" style={{ maxWidth: 280 }}>
            <Select value={f.assignee} onChange={set("assignee")}>{D.team.map((u) => <option key={u}>{u}</option>)}</Select>
          </Field>
        </div>
      </Section>
    </Modal>
  );
}
window.PropertyForm = PropertyForm;

/* ============================================================
   FOLLOW-UP — set on a property
   ============================================================ */
function FollowUpForm({ property }) {
  const D = window.PT_DATA;
  const base = "/properties/" + property.id;
  const [f, setF] = useState({ subject: "", date: "", assignee: D.user.name });
  function fmt(d) {
    if (!d) return "—";
    const dt = new Date(d + "T00:00:00");
    return dt.toLocaleDateString("en-US", { month: "short", day: "2-digit" });
  }
  function save() {
    property.followDate = fmt(f.date);
    property.overdue = false;
    property.notes = property.notes || [];
    property.notes.unshift({ author: D.user.name, time: "Just now", subject: f.subject || "Follow-up scheduled", body: "Follow-up set for " + fmt(f.date) + ".", emailed: 0, follow: fmt(f.date), assignee: f.assignee || "Unassigned" });
    PTStore.bump();
    pushToast({ tone: "success", title: "Follow-up set", body: "Due " + fmt(f.date) + (f.assignee ? " · " + f.assignee : "") + "." });
    closeOverlay(base);
  }
  return (
    <Modal width={460} icon="calendar-clock" iconTone="action" title="Set follow-up" subtitle={property.address} onClose={() => closeOverlay(base)}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay(base)}>Cancel</Button>
        <Button variant="primary" icon="check" onClick={save} disabled={!f.date}>Set follow-up</Button>
      </>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Subject"><Input placeholder="e.g. Call seller about counter" value={f.subject} onChange={(e) => setF((s) => ({ ...s, subject: e.target.value }))} /></Field>
        <Field label="Follow-up date" required><Input type="date" icon="calendar" value={f.date} onChange={(e) => setF((s) => ({ ...s, date: e.target.value }))} /></Field>
        <Field label="Assign to" hint="Leave on a teammate, or pick a non-user task label.">
          <Select value={f.assignee} onChange={(e) => setF((s) => ({ ...s, assignee: e.target.value }))}>
            <option value="">Unassigned (anyone can complete)</option>
            <optgroup label="Team">{D.team.map((u) => <option key={u} value={u}>{u}</option>)}</optgroup>
            <optgroup label="Task labels">{D.taskLabels.map((t) => <option key={t} value={t}>{t}</option>)}</optgroup>
          </Select>
        </Field>
      </div>
    </Modal>
  );
}
window.FollowUpForm = FollowUpForm;

/* ============================================================
   CONTACT — add / edit (Contacts screen)
   ============================================================ */
function ContactForm({ idx }) {
  const D = window.PT_DATA;
  const existing = idx != null ? D.allContacts[idx] : null;
  const roles = ["Homeowner", "Seller", "Buyer", "Agent", "Attorney", "Lender", "Investor"];
  const [f, setF] = useState(() => ({
    name: existing?.name || "", role: existing?.role || "Homeowner", phone: existing?.phone || "", email: existing?.email || "",
    quick: existing?.quick || "", rating: existing?.rating || 3, isBuyer: existing?.isBuyer || false, isSeller: existing?.isSeller || false,
    masked: existing?.masked || false, notes: existing?.notes || "",
  }));
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  function save() {
    const rec = { name: f.name, role: f.role, phone: f.phone, email: f.email, quick: f.quick, rating: +f.rating, isBuyer: f.isBuyer, isSeller: f.isSeller, masked: f.masked, notes: f.notes, deals: existing?.deals || 0 };
    if (existing) { Object.assign(existing, rec); pushToast({ tone: "success", title: "Contact updated", body: f.name + " was saved." }); }
    else { D.allContacts.unshift(rec); pushToast({ tone: "success", title: "Contact added", body: f.name + " was added to your CRM." }); }
    PTStore.bump();
    closeOverlay("/contacts");
  }
  return (
    <Modal width={560} icon={existing ? "pencil" : "user-plus"} title={existing ? "Edit contact" : "Add contact"} subtitle={existing ? f.role : "New CRM record"} onClose={() => closeOverlay("/contacts")}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay("/contacts")}>Cancel</Button>
        <Button variant="primary" icon="check" onClick={save} disabled={!f.name || !f.email}>{existing ? "Save changes" : "Add contact"}</Button>
      </>}>
      <Section title="Identity">
        <Grid cols={2}>
          <Field label="Full name" required><Input placeholder="Robert Hale" value={f.name} onChange={set("name")} /></Field>
          <Field label="Contact type"><Select value={f.role} onChange={set("role")}>{roles.map((r) => <option key={r}>{r}</option>)}</Select></Field>
        </Grid>
      </Section>
      <Section title="Details">
        <Grid cols={2}>
          <Field label="Phone"><Input icon="phone" value={f.phone} onChange={set("phone")} /></Field>
          <Field label="Email" required><Input icon="mail" value={f.email} onChange={set("email")} /></Field>
        </Grid>
      </Section>
      <Section title="CRM">
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Field label="Quick comment" hint="Surfaced in context on properties (Fix #12)."><Input icon="message-square-text" value={f.quick} onChange={set("quick")} /></Field>
          <Grid cols={2}>
            <Field label="Rating"><Select value={f.rating} onChange={set("rating")}>{[1, 2, 3, 4, 5].map((n) => <option key={n} value={n}>{n} star{n > 1 ? "s" : ""}</option>)}</Select></Field>
            <div style={{ display: "flex", alignItems: "flex-end", gap: 18, paddingBottom: 4 }}>
              <Checkbox checked={f.isBuyer} onChange={(v) => setF((s) => ({ ...s, isBuyer: v }))} label="Buyer" />
              <Checkbox checked={f.isSeller} onChange={(v) => setF((s) => ({ ...s, isSeller: v }))} label="Seller" />
            </div>
          </Grid>
          <Toggle checked={f.masked} onChange={(v) => setF((s) => ({ ...s, masked: v }))} label="Mask sensitive fields (private)" />
          <Field label="Contact notes"><Textarea rows={3} value={f.notes} onChange={set("notes")} /></Field>
        </div>
      </Section>
    </Modal>
  );
}
window.ContactForm = ContactForm;

/* ============================================================
   TASK — add / edit
   ============================================================ */
function TaskForm({ idx }) {
  const D = window.PT_DATA;
  const existing = idx != null ? D.tasks[idx] : null;
  const [f, setF] = useState(() => ({
    title: existing?.title || "", property: existing?.property || D.properties[0].address,
    assignee: existing?.assignee ?? D.user.name, due: existing?.dueISO || "", dueLabel: existing?.due || "", desc: existing?.desc || "",
  }));
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  function fmt(d) { if (!d) return "—"; return new Date(d + "T00:00:00").toLocaleDateString("en-US", { month: "short", day: "2-digit" }); }
  function save() {
    const rec = { title: f.title, property: f.property, assignee: f.assignee, due: f.due ? fmt(f.due) : (f.dueLabel || "—"), dueISO: f.due, desc: f.desc, done: existing?.done || false, overdue: existing?.overdue || false };
    if (existing) { Object.assign(existing, rec); pushToast({ tone: "success", title: "Task updated", body: f.title }); }
    else { D.tasks.unshift(rec); pushToast({ tone: "success", title: "Task created", body: f.title }); }
    PTStore.bump();
    closeOverlay("/tasks");
  }
  return (
    <Modal width={520} icon={existing ? "pencil" : "plus"} title={existing ? "Edit task" : "New task"} onClose={() => closeOverlay("/tasks")}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay("/tasks")}>Cancel</Button>
        <Button variant="primary" icon="check" onClick={save} disabled={!f.title}>{existing ? "Save changes" : "Create task"}</Button>
      </>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Title" required><Input placeholder="e.g. Order title search" value={f.title} onChange={set("title")} /></Field>
        <Field label="Related property"><Select value={f.property} onChange={set("property")}>{D.properties.map((p) => <option key={p.id}>{p.address}</option>)}</Select></Field>
        <Grid cols={2}>
          <Field label="Assign to">
            <Select value={f.assignee} onChange={set("assignee")}>
              <option value="">Unassigned</option>
              <optgroup label="Team">{D.team.map((u) => <option key={u} value={u}>{u}</option>)}</optgroup>
              <optgroup label="Task labels">{D.taskLabels.map((t) => <option key={t} value={t}>{t}</option>)}</optgroup>
            </Select>
          </Field>
          <Field label="Due date"><Input type="date" icon="calendar" value={f.due} onChange={set("due")} /></Field>
        </Grid>
        <Field label="Description"><Textarea rows={3} value={f.desc} onChange={set("desc")} /></Field>
      </div>
    </Modal>
  );
}
window.TaskForm = TaskForm;

/* ============================================================
   PAGE — add / edit (Site & branding)
   ============================================================ */
function PageForm({ idx }) {
  const D = window.PT_DATA;
  const existing = idx != null ? D.site.pages[idx] : null;
  const [f, setF] = useState(() => ({ title: existing?.title || "", path: existing?.path || "", status: existing?.status || "Draft", menu: existing?.menu ?? true, meta: existing?.meta || "" }));
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  function slugify(t) { return "/" + t.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); }
  function save() {
    const rec = { title: f.title, path: f.path || slugify(f.title), status: f.status, menu: f.menu, meta: f.meta, updated: "Just now" };
    if (existing) { Object.assign(existing, rec); pushToast({ tone: "success", title: "Page saved", body: f.title }); }
    else { D.site.pages.push(rec); pushToast({ tone: "success", title: "Page created", body: f.title }); }
    PTStore.bump();
    closeOverlay("/website/site");
  }
  return (
    <Modal width={520} icon={existing ? "pencil" : "file-text"} title={existing ? "Edit page" : "New page"} onClose={() => closeOverlay("/website/site")}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay("/website/site")}>Cancel</Button>
        <Button variant="primary" icon="check" onClick={save} disabled={!f.title}>{existing ? "Save page" : "Create page"}</Button>
      </>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Page title" required><Input placeholder="About us" value={f.title} onChange={set("title")} /></Field>
        <Grid cols={2}>
          <Field label="URL path" hint="Auto from title if blank."><Input icon="link" placeholder={f.title ? slugify(f.title) : "/about-us"} value={f.path} onChange={set("path")} /></Field>
          <Field label="Status"><Select value={f.status} onChange={set("status")}><option>Draft</option><option>Published</option></Select></Field>
        </Grid>
        <Field label="Meta description" hint="Shown in search results."><Textarea rows={2} value={f.meta} onChange={set("meta")} /></Field>
        <Toggle checked={f.menu} onChange={(v) => setF((s) => ({ ...s, menu: v }))} label="Show in site navigation" />
      </div>
    </Modal>
  );
}
window.PageForm = PageForm;

/* ============================================================
   BLOG POST — write / edit
   ============================================================ */
function PostForm({ idx }) {
  const D = window.PT_DATA;
  const existing = idx != null ? D.blogPosts[idx] : null;
  const cats = ["Selling", "Market", "Guides", "Company"];
  const [f, setF] = useState(() => ({ title: existing?.title || "", cat: existing?.cat || "Selling", author: existing?.author || D.user.name, status: existing?.status || "Draft", date: existing?.date || "—", excerpt: existing?.excerpt || "", body: existing?.body || "" }));
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  function save() {
    const rec = { title: f.title, cat: f.cat, author: f.author, status: f.status, date: f.status === "Published" ? "Jun 19, 2026" : f.date, views: existing?.views || 0, excerpt: f.excerpt, body: f.body };
    if (existing) { Object.assign(existing, rec); pushToast({ tone: "success", title: "Post saved", body: f.title }); }
    else { D.blogPosts.unshift(rec); pushToast({ tone: "success", title: f.status === "Published" ? "Post published" : "Draft saved", body: f.title }); }
    PTStore.bump();
    closeOverlay("/website/blog");
  }
  return (
    <Modal width={640} icon={existing ? "pencil" : "newspaper"} title={existing ? "Edit post" : "Write post"} onClose={() => closeOverlay("/website/blog")}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay("/website/blog")}>Cancel</Button>
        <Button variant="primary" icon="check" onClick={save} disabled={!f.title}>{existing ? "Save post" : "Save post"}</Button>
      </>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Title" required><Input placeholder="5 signs it's time to sell as-is" value={f.title} onChange={set("title")} /></Field>
        <Grid cols={3}>
          <Field label="Category"><Select value={f.cat} onChange={set("cat")}>{cats.map((c) => <option key={c}>{c}</option>)}</Select></Field>
          <Field label="Author"><Select value={f.author} onChange={set("author")}>{D.team.map((u) => <option key={u}>{u}</option>)}</Select></Field>
          <Field label="Status"><Select value={f.status} onChange={set("status")}><option>Draft</option><option>Scheduled</option><option>Published</option></Select></Field>
        </Grid>
        {f.status === "Scheduled" && <Field label="Publish date"><Input type="date" icon="calendar" value={f.dateISO || ""} onChange={(e) => setF((s) => ({ ...s, dateISO: e.target.value, date: new Date(e.target.value + "T00:00:00").toLocaleDateString("en-US", { month: "short", day: "2-digit", year: "numeric" }) }))} /></Field>}
        <Field label="Excerpt" hint="Shown on the blog index."><Textarea rows={2} value={f.excerpt} onChange={set("excerpt")} /></Field>
        <Field label="Body"><Textarea rows={6} placeholder="Write your post…" value={f.body} onChange={set("body")} /></Field>
      </div>
    </Modal>
  );
}
window.PostForm = PostForm;

/* ============================================================
   NEW LEAD — view & convert (Dashboard alert click)
   ============================================================ */
function LeadModal({ idx }) {
  const D = window.PT_DATA;
  const lead = D.leads[idx];
  if (!lead) { closeOverlay("/dashboard"); return null; }
  const hasProperty = lead.address && lead.address !== "—";

  function convert() {
    // Attach the submitter as a contact (Fix #11)
    D.allContacts.unshift({ name: lead.name, role: "Seller", phone: lead.phone, email: (lead.name.toLowerCase().replace(/\s+/g, ".") + "@example.com"), quick: "Came in via " + lead.source, rating: 3, deals: hasProperty ? 1 : 0, masked: false });
    let newId = null;
    if (hasProperty) {
      newId = nextPropId();
      const parts = lead.address.split(",").map((s) => s.trim());
      D.properties.unshift({
        id: newId, thumb: DEFAULT_THUMB, address: parts[0] || lead.address, city: parts[1] || "", state: (parts[2] || "").split(" ")[0] || "", zip: "", county: "",
        status: "lead", type: "Single Family", deal: "Buyer Lead", source: lead.source, motivation: "Medium",
        ask: 0, offer: 0, arv: 0, beds: 0, baths: 0, sqft: 0, year: 0, lot: "—", followDate: "Today", overdue: true,
        published: false, lat: 40.0 + (Math.random() - 0.5), lng: -82.9 + (Math.random() - 0.5),
        contacts: [{ name: lead.name, role: "Seller", phone: lead.phone, email: (lead.name.toLowerCase().replace(/\s+/g, ".") + "@example.com"), quick: "Webform lead — " + lead.source, rating: 3, masked: false }],
        notes: [{ author: "System", time: "Just now", subject: "New lead from " + lead.source, body: lead.name + " submitted the " + lead.source + ". Owner notified.", emailed: 0, follow: "Today", assignee: D.user.name }],
      });
    }
    D.leads.splice(idx, 1);
    PTStore.bump();
    pushToast({ tone: "success", title: "Lead converted", body: hasProperty ? "Property + contact created, owner notified." : lead.name + " added as a contact." });
    if (newId) navigate("/properties/" + newId);
    else navigate("/contacts");
  }

  return (
    <Modal width={520} icon="bell" iconTone="info" title="New lead" subtitle={lead.time} onClose={() => closeOverlay("/dashboard")}
      footer={<>
        <Button variant="secondary" onClick={() => closeOverlay("/dashboard")}>Close</Button>
        <Button variant="primary" icon={hasProperty ? "building-2" : "user-plus"} onClick={convert}>{hasProperty ? "Create property & contact" : "Add as contact"}</Button>
      </>}>
      <div style={{ display: "flex", gap: 13, alignItems: "center", marginBottom: 16 }}>
        <Avatar name={lead.name} size="lg" />
        <div>
          <div style={{ fontSize: "var(--text-lg)", fontWeight: 700, color: "var(--text-strong)" }}>{lead.name}</div>
          <div style={{ marginTop: 3 }}><Badge tone="brand" size="sm" icon="clipboard-list">{lead.source}</Badge></div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
        <div><div style={{ fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", color: "var(--text-subtle)", fontWeight: 700 }}>Phone</div><div className="tnum" style={{ fontSize: "var(--text-base)", color: "var(--text-strong)" }}>{lead.phone}</div></div>
        <div><div style={{ fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", color: "var(--text-subtle)", fontWeight: 700 }}>Property</div><div style={{ fontSize: "var(--text-base)", color: "var(--text-strong)" }}>{hasProperty ? lead.address : "No property submitted"}</div></div>
      </div>
      <Banner tone="info" title="What happens when you convert">
        We create a contact{hasProperty ? " and a property lead, attach the submitter to it," : ","} and notify the assigned owner — exactly what a real webform submission triggers (Fix #1 / #11).
      </Banner>
    </Modal>
  );
}
window.LeadModal = LeadModal;

/* ============================================================
   Routed wrappers for existing modals (Note editor, property Contact card)
   ============================================================ */
function NoteEditorRouted({ property }) {
  const base = "/properties/" + property.id;
  return (
    <NoteEditor property={property} open={true} onClose={() => closeOverlay(base)}
      onSaved={(res) => {
        property.notes = property.notes || [];
        property.notes.unshift({ author: window.PT_DATA.user.name, time: "Just now", subject: res.subject || "Note", body: res.body || "", emailed: res.emailed || 0, follow: res.follow || "—", assignee: res.assignee || "Unassigned" });
        PTStore.bump();
        pushToast({ tone: "success", title: "Note saved", body: res.emailed ? res.emailed + " contacts emailed." : "No contacts emailed." });
        closeOverlay(base);
      }} />
  );
}
window.NoteEditorRouted = NoteEditorRouted;

function ContactModalRouted({ property, cidx }) {
  const base = "/properties/" + property.id;
  const c = property.contacts[cidx];
  if (!c) { closeOverlay(base); return null; }
  return <ContactModal contact={c} open={true} onClose={() => closeOverlay(base)} />;
}
window.ContactModalRouted = ContactModalRouted;
