/* NoteEditor + ContactModal + template picker. window.NoteEditor, window.ContactModal */
const { useState } = React;
function AssigneePicker({ value, onChange }) {
  const d = window.PT_DATA;
  return (
    <Select value={value} onChange={(e) => onChange(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 (no user)">
        {d.taskLabels.map((t) => <option key={t} value={t}>{t}</option>)}
      </optgroup>
    </Select>
  );
}

function NoteEditor({ property: p, open, onClose, onSaved }) {
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const [email, setEmail] = useState(true);
  const [assignee, setAssignee] = useState("Dana Reyes");
  const [follow, setFollow] = useState("");
  const [warn, setWarn] = useState(false);
  if (!open) return null;

  const recipients = p.contacts.filter((c) => c.email);
  const hasBody = body.trim().length > 0;

  function attemptSave() {
    if (!hasBody) { setWarn(true); return; }
    onSaved({ emailed: email ? recipients.length : 0, subject: subject || "Note", body, assignee, follow: follow ? new Date(follow + "T00:00:00").toLocaleDateString("en-US", { month: "short", day: "2-digit" }) : "—" });
  }

  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()} style={{ width: "100%", maxWidth: 600, maxHeight: "90vh", overflow: "auto", background: "var(--surface-card)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)", animation: "ptdialog var(--dur-base) var(--ease-out)" }}>
          {/* header */}
          <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "18px 22px 14px", borderBottom: "1px solid var(--border-subtle)" }}>
            <span style={{ width: 38, height: 38, borderRadius: "var(--radius-lg)", background: "var(--ember-50)", color: "var(--ember-600)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="pencil" size={19} /></span>
            <div style={{ flex: 1 }}>
              <h2 style={{ fontSize: "var(--text-lg)", fontWeight: 700, color: "var(--text-strong)" }}>Add note</h2>
              <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{p.address} · {p.id}</div>
            </div>
            <IconButton icon="x" label="Close" onClick={onClose} />
          </div>

          {/* body */}
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16 }}>
            <Field label="Subject">
              <Input placeholder="e.g. Spoke with the seller" value={subject} onChange={(e) => setSubject(e.target.value)} />
            </Field>
            <Field label="Note" hint="Paste from anywhere — pasted text counts as content.">
              <Textarea rows={5} placeholder="Write a note…" value={body} invalid={warn && !hasBody}
                onChange={(e) => setBody(e.target.value)}
                onPaste={(e) => { const t = e.clipboardData.getData("text"); if (t) { e.preventDefault(); setBody((b) => b + t); } }} />
            </Field>

            {/* auto-email */}
            <div style={{ padding: 14, borderRadius: "var(--radius-md)", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)" }}>
              <Toggle checked={email} onChange={setEmail} label="Email the property's contacts" />
              {email && (
                <div style={{ marginTop: 10, display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
                  <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>Sends to:</span>
                  {recipients.map((c) => <Badge key={c.name} tone="brand" size="sm">{c.name}</Badge>)}
                  <span style={{ fontSize: "var(--text-xs)", color: "var(--text-subtle)" }}>· from {window.PT_DATA.user.name}</span>
                </div>
              )}
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Assign to"><AssigneePicker value={assignee} onChange={setAssignee} /></Field>
              <Field label="Follow-up date"><Input type="date" icon="calendar" value={follow} onChange={(e) => setFollow(e.target.value)} /></Field>
            </div>
          </div>

          {/* footer */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, padding: "14px 22px", background: "var(--surface-sunken)", borderTop: "1px solid var(--border-subtle)" }}>
            <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", display: "inline-flex", alignItems: "center", gap: 5 }}>
              <Icon name="user" size={13} /> Authored by {window.PT_DATA.user.name}
            </span>
            <div style={{ display: "flex", gap: 8 }}>
              <Button variant="secondary" onClick={onClose}>Cancel</Button>
              <Button variant="primary" icon={email ? "mail" : "check"} onClick={attemptSave}>{email ? `Email ${recipients.length} & save` : "Save note"}</Button>
            </div>
          </div>
        </div>
      </div>

      <Dialog open={warn} onClose={() => setWarn(false)} tone="warning" icon="triangle-alert" title="This note has no content"
        footer={<>
          <Button variant="secondary" onClick={() => setWarn(false)}>Keep editing</Button>
          <Button variant="primary" onClick={onClose}>Discard note</Button>
        </>}>
        The note has a subject but no body, so nothing will be saved. Add some text, or discard it.
      </Dialog>
    </>
  );
}
window.NoteEditor = NoteEditor;

function Stars({ n }) {
  return <span style={{ display: "inline-flex", gap: 1 }}>{[1,2,3,4,5].map(i => <Icon key={i} name="star" size={14} color={i <= n ? "var(--amber-500)" : "var(--slate-200)"} style={{ fill: i <= n ? "var(--amber-500)" : "none" }} />)}</span>;
}

function ContactModal({ contact: c, open, onClose }) {
  if (!open || !c) return null;
  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()} style={{ width: "100%", maxWidth: 520, 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", gap: 13, alignItems: "center", padding: 20, background: "var(--harbor-900)" }}>
          <Avatar name={c.name} size="lg" />
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <h2 style={{ fontSize: "var(--text-lg)", fontWeight: 700, color: "#fff" }}>{c.name}</h2>
              <Badge tone="brand" size="sm" solid>{c.role}</Badge>
            </div>
            <div style={{ marginTop: 3 }}><Stars n={c.rating} /></div>
          </div>
          <IconButton icon="x" label="Close" onClick={onClose} style={{ color: "var(--harbor-200)" }} />
        </div>
        <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <Field label="Phone"><Input defaultValue={c.masked ? "" : c.phone} placeholder={c.masked ? "(hidden)" : ""} icon="phone" /></Field>
            <Field label="Email"><Input defaultValue={c.email} icon="mail" /></Field>
          </div>
          <Field label="Quick comment" hint="Editable here and on the property — Fix #12">
            <Input defaultValue={c.quick} icon="message-square-text" />
          </Field>
          <Field label="Contact notes">
            <Textarea rows={3} defaultValue={"Full contact record — edit without leaving the property (Fix #13)."} />
          </Field>
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "14px 20px", background: "var(--surface-sunken)", borderTop: "1px solid var(--border-subtle)" }}>
          <Button variant="secondary" onClick={onClose}>Close</Button>
          <Button variant="primary" icon="check">Save contact</Button>
        </div>
      </div>
    </div>
  );
}
window.ContactModal = ContactModal;
