// form.jsx — entry form pieces

const FUEL_TYPES = [
  { id: "natgas",   label: "Natural gas", color: "#3B82C4" },
  { id: "electric", label: "Electric", color: "#D9A23B" },
  { id: "oil",      label: "Oil",      color: "#7A4F2A" },
  { id: "propane",  label: "Propane",  color: "#C24E2E" },
  { id: "wood",     label: "Wood",     color: "#5E6F4F" },
  { id: "kerosene", label: "Kerosene", color: "#9C6BB0" },
  { id: "other",    label: "Other",    color: "#8A958F" },
];

const CALENDARS = [
  { id: "wx",       label: "WX Field Schedule",  color: "#2F6F5C" },
  { id: "intake",   label: "Customer Intake",    color: "#3B82C4" },
  { id: "audit",    label: "Energy Audits",      color: "#D9A23B" },
  { id: "personal", label: "My calendar",        color: "#9C6BB0" },
];

const EVENT_COLORS = [
  { id: "sage",    val: "#2F6F5C" },
  { id: "blue",    val: "#3B82C4" },
  { id: "amber",   val: "#D9A23B" },
  { id: "coral",   val: "#C24E2E" },
  { id: "plum",    val: "#9C6BB0" },
  { id: "olive",   val: "#5E6F4F" },
  { id: "graphite",val: "#4A5752" },
];

const REMINDER_PRESETS = [10, 30, 60, 1440]; // minutes

/* ---------- icons ---------- */
const Icon = {
  cal: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="5" width="18" height="16" rx="3"></rect>
      <path d="M3 10h18M8 3v4M16 3v4"></path>
    </svg>
  ),
  clock: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path>
    </svg>
  ),
  hourglass: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M6 3h12M6 21h12M7 3v3a5 5 0 0 0 10 0V3M7 21v-3a5 5 0 0 1 10 0v3"></path>
    </svg>
  ),
  pin: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 22s7-7.5 7-13a7 7 0 1 0-14 0c0 5.5 7 13 7 13z"></path>
      <circle cx="12" cy="9" r="2.5"></circle>
    </svg>
  ),
  bell: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8z"></path>
      <path d="M10 21a2 2 0 0 0 4 0"></path>
    </svg>
  ),
  paperclip: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M21 11.5 12.5 20a5 5 0 0 1-7-7L14 4a3.5 3.5 0 0 1 5 5l-8.5 8.5a2 2 0 0 1-3-3L15 6.5"></path>
    </svg>
  ),
  user: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="8" r="4"></circle><path d="M4 21a8 8 0 0 1 16 0"></path>
    </svg>
  ),
  alert: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3 2 21h20L12 3z"></path><path d="M12 10v5M12 18v.01"></path>
    </svg>
  ),
  plus: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}>
      <path d="M12 5v14M5 12h14"></path>
    </svg>
  ),
  x: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}>
      <path d="M6 6l12 12M18 6 6 18"></path>
    </svg>
  ),
  doc: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"></path>
      <path d="M14 3v5h5"></path>
    </svg>
  ),
  upload: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 16V4M6 10l6-6 6 6"></path><path d="M4 20h16"></path>
    </svg>
  ),
  check: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 12l5 5L20 7"></path>
    </svg>
  ),
  spark: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"></path>
    </svg>
  ),
};

/* ---------- helpers ---------- */
function fmtPhone(v) {
  const d = (v || "").replace(/\D/g, "").slice(0, 10);
  if (d.length <= 3) return d;
  if (d.length <= 6) return `(${d.slice(0,3)}) ${d.slice(3)}`;
  return `(${d.slice(0,3)}) ${d.slice(3,6)}-${d.slice(6)}`;
}
function fmtAmount(v) {
  const n = (v || "").replace(/[^\d.]/g, "");
  const [int, dec] = n.split(".");
  const grouped = (int || "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  if (dec === undefined) return grouped;
  return grouped + "." + dec.slice(0, 2);
}
function fmtDateLong(d) {
  if (!d) return "—";
  const date = new Date(d);
  return date.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
}
function fmtTime(t) {
  if (!t) return "—";
  const [h, m] = t.split(":").map(Number);
  const ampm = h >= 12 ? "PM" : "AM";
  const hh = ((h + 11) % 12) + 1;
  return `${hh}:${String(m).padStart(2,"0")} ${ampm}`;
}
function durationLabel(mins) {
  if (mins < 60) return `${mins} min`;
  const h = Math.floor(mins / 60), m = mins % 60;
  return m ? `${h}h ${m}m` : `${h}h`;
}
function endTime(start, mins) {
  if (!start) return "";
  const [h, m] = start.split(":").map(Number);
  const total = h * 60 + m + mins;
  const eh = Math.floor(total / 60) % 24;
  const em = total % 60;
  return `${String(eh).padStart(2,"0")}:${String(em).padStart(2,"0")}`;
}

/* ---------- field components ---------- */
function Field({ label, hint, required, children, htmlFor }) {
  return (
    <div className="field">
      <label className="field-label" htmlFor={htmlFor}>
        <span>{label}{required && <span className="req">*</span>}</span>
        {hint && <span className="hint">{hint}</span>}
      </label>
      {children}
    </div>
  );
}

function ChipGroup({ value, onChange, options, multi }) {
  const arr = Array.isArray(value) ? value : (value ? [value] : []);
  const toggle = (id) => {
    if (multi) {
      onChange(arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id]);
    } else {
      onChange(id);
    }
  };
  return (
    <div className="chip-row">
      {options.map(o => (
        <button key={o.id} type="button"
          className="chip"
          aria-pressed={arr.includes(o.id)}
          onClick={() => toggle(o.id)}
          style={{ "--c": o.color }}>
          {o.color && <span className="swatch"></span>}
          {o.label}
        </button>
      ))}
    </div>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div className="segmented" role="radiogroup">
      {options.map(o => (
        <button key={o.id} type="button"
          aria-pressed={value === o.id}
          onClick={() => onChange(o.id)}>
          {o.label}
        </button>
      ))}
    </div>
  );
}

function Swatches({ value, onChange, options }) {
  return (
    <div className="swatches">
      {options.map(o => (
        <button key={o.id} type="button"
          className="sw"
          aria-pressed={value === o.id}
          onClick={() => onChange(o.id)}
          style={{ "--c": o.val }}
          aria-label={o.id}></button>
      ))}
    </div>
  );
}

/* ---------- big form ---------- */
function EntryForm({ data, set, onSubmit, layout, requireContract }) {
  const [dragOver, setDragOver] = React.useState(false);
  const fileRef = React.useRef(null);

  const addFiles = (list) => {
    const arr = Array.from(list || []).map(f => ({
      name: f.name, size: f.size, id: Math.random().toString(36).slice(2),
    }));
    set("files", [...(data.files || []), ...arr]);
  };

  const valid =
    data.name.trim().length > 0 &&
    data.zip.trim().length >= 5 &&
    data.date && data.time &&
    (!requireContract || data.amount.length > 0);

  return (
    <form
      className="card"
      onSubmit={(e) => { e.preventDefault(); if (valid) onSubmit(); }}>

      {/* ── Customer ───────────────────────────── */}
      <div className="section-row">
        <span className="section-label">Customer</span>
        <span className="section-step">i.</span>
      </div>

      <div className="row">
        <Field label="Customer name" required>
          <input className="input"
            placeholder="e.g. Margaret Holloway"
            value={data.name}
            onChange={(e) => set("name", e.target.value)} />
        </Field>
      </div>

      <div className="row cols-2" style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Phone">
          <input className="input"
            placeholder="(207) 555-0142"
            value={data.phone}
            onChange={(e) => set("phone", fmtPhone(e.target.value))}
            inputMode="tel" />
        </Field>
        <Field label="Email">
          <input className="input"
            type="email"
            placeholder="margaret@example.com"
            value={data.email}
            onChange={(e) => set("email", e.target.value)} />
        </Field>
      </div>

      <div className="row" style={{ marginTop: "var(--gap-row)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 110px", gap: 10 }} className="addr-grid">
          <Field label="Service address" required>
            <input className="input"
              placeholder="124 Pine Ridge Rd"
              value={data.address}
              onChange={(e) => set("address", e.target.value)} />
          </Field>
          <Field label="City / Town" hint={data.zip && !data.town ? "no match" : ""}>
            <input className="input"
              placeholder="auto from ZIP"
              value={data.town}
              onChange={(e) => set("town", e.target.value)} />
          </Field>
          <Field label="ZIP" required>
            <input className="input"
              placeholder="01001"
              value={data.zip}
              onChange={(e) => {
                const z = e.target.value.replace(/[^\d-]/g, "").slice(0, 10);
                set("zip", z);
                const key = z.padStart(5, "0").slice(0, 5);
                const hit = (window.ZIP_DATA || {})[key];
                if (hit && z.length >= 5) {
                  set("town", hit.city || "");
                  if (hit.gas) set("gasUtility", hit.gas);
                  if (hit.electric) set("electricUtility", hit.electric);
                }
              }}
              inputMode="numeric" />
          </Field>
        </div>
      </div>

      <div className="row cols-2" style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Gas utility company" hint={data.zip && !data.gasUtility ? "no match" : ""}>
          <div className="select-wrap">
            <select className="select"
              value={data.gasUtility}
              onChange={(e) => set("gasUtility", e.target.value)}>
              <option value="">— select —</option>
              {(window.GAS_UTILS || []).map(u => (
                <option key={u} value={u}>{u}</option>
              ))}
            </select>
          </div>
        </Field>
        <Field label="Electric utility" hint={data.zip && !data.electricUtility ? "no match" : ""}>
          <div className="select-wrap">
            <select className="select"
              value={data.electricUtility}
              onChange={(e) => set("electricUtility", e.target.value)}>
              <option value="">— select —</option>
              {(window.ELECTRIC_UTILS || []).map(u => (
                <option key={u} value={u}>{u}</option>
              ))}
            </select>
          </div>
        </Field>
      </div>

      <hr className="hr" />

      {/* ── Job details ────────────────────────── */}
      <div className="section-row">
        <span className="section-label">Job details</span>
        <span className="section-step">ii.</span>
      </div>

      <Field label="Heating fuel">
        <ChipGroup
          options={FUEL_TYPES}
          value={data.fuel}
          onChange={(v) => set("fuel", v)} />
      </Field>

      <div className="row cols-2" style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Contract amount" required={requireContract}>
          <div className="amount-field">
            <span className="currency">$</span>
            <input
              placeholder="0"
              value={data.amount}
              onChange={(e) => set("amount", fmtAmount(e.target.value))}
              inputMode="decimal" />
            <span className="cents">USD</span>
          </div>
        </Field>
        <Field label="WX status">
          <div className="select-wrap">
            <select className="select"
              value={data.jobType}
              onChange={(e) => set("jobType", e.target.value)}>
              <option value="waiting">Waiting to schedule</option>
              <option value="scheduled">Scheduled</option>
              <option value="callback">Call back</option>
              <option value="roadblock">Road block pending</option>
              <option value="reschedule">Reschedule</option>
              <option value="canceled">Canceled</option>
              <option value="walk">WALK</option>
              <option value="completed">Completed</option>
              <option value="invoiced">Invoiced</option>
              <option value="paid">Paid from vendor</option>
            </select>
          </div>
        </Field>
      </div>

      <div className="row" style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Road block status" hint="any barriers at the property?">
          <div className={"flag-row " + (data.roadblock !== "none" ? "on" : "")}>
            <span className="flag-icon">
              {data.roadblock === "none" ? <Icon.check /> :
               data.roadblock === "cleared" ? <Icon.check /> : <Icon.alert />}
            </span>
            <div className="flag-text">
              {data.roadblock === "none" && (<><b>No road blocks</b><span>Site is ready for crew</span></>)}
              {data.roadblock === "cleared" && (<><b>Cleared</b><span>Barriers identified &amp; resolved</span></>)}
              {data.roadblock === "not-cleared" && (<><b>Not cleared</b><span>Barriers must be resolved before crew arrives</span></>)}
            </div>
            <Segmented
              value={data.roadblock}
              onChange={(v) => set("roadblock", v)}
              options={[
                { id: "none",        label: "None" },
                { id: "cleared",     label: "Cleared" },
                { id: "not-cleared", label: "Not cleared" },
              ]}
            />
          </div>
        </Field>
      </div>

      {data.roadblock !== "none" && (
        <div className="row" style={{ marginTop: "var(--gap-row)" }}>
          <Field label="Barriers on site" hint="check each barrier and note if the form is on file">
            <div className="barrier-list">
              {[
                { id: "recessed",    label: "Recessed lighting" },
                { id: "knob-tube",   label: "Knob & tube wiring" },
                { id: "mold",        label: "Mold" },
                { id: "vermiculite", label: "Vermiculite" },
                { id: "structural",  label: "Structural" },
              ].map(b => {
                const state = (data.barriers || {})[b.id] || { present: false, signed: null };
                const updateBarrier = (patch) =>
                  set("barriers", { ...(data.barriers || {}), [b.id]: { ...state, ...patch } });
                return (
                  <div key={b.id} className={"barrier-row " + (state.present ? "is-on" : "")}>
                    <button type="button"
                      className={"barrier-check " + (state.present ? "is-on" : "")}
                      onClick={() => updateBarrier({ present: !state.present })}
                      aria-pressed={state.present}>
                      {state.present && <Icon.check />}
                    </button>
                    <span className="barrier-label">{b.label}</span>
                    {state.present && (
                      <div className="barrier-form">
                        <span className="barrier-form-q">Barrier form signed &amp; on record?</span>
                        <div className="segmented sm">
                          <button type="button"
                            aria-pressed={state.signed === true}
                            onClick={() => updateBarrier({ signed: true })}>Yes</button>
                          <button type="button"
                            aria-pressed={state.signed === false}
                            onClick={() => updateBarrier({ signed: false })}>No</button>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </Field>
        </div>
      )}

      <hr className="hr" />

      {/* ── Schedule ───────────────────────────── */}
      <div className="section-row">
        <span className="section-label">Schedule WX work</span>
        <span className="section-step">iii.</span>
      </div>

      <div className="dt-row">
        <div className="dt-field">
          <Icon.cal />
          <input
            type="date"
            value={data.date}
            onChange={(e) => set("date", e.target.value)} />
        </div>
        <div className="dt-field">
          <Icon.clock />
          <input
            type="time"
            value={data.time}
            onChange={(e) => set("time", e.target.value)} />
        </div>
        <div className="dt-field">
          <Icon.hourglass />
          <select
            value={data.duration}
            onChange={(e) => set("duration", parseInt(e.target.value, 10))}
            style={{ flex: 1, border: 0, background: "transparent", outline: "none", fontSize: "var(--field-size)", fontWeight: 500, fontFamily: "inherit", color: "var(--ink)" }}>
            <option value="30">30 min</option>
            <option value="60">1 hour</option>
            <option value="90">1h 30m</option>
            <option value="120">2 hours</option>
            <option value="180">3 hours</option>
            <option value="240">4 hours</option>
            <option value="480">Full day (8h)</option>
          </select>
        </div>
      </div>

      <div className="row" style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Calendar">
          <div className="select-wrap">
            <select className="select"
              value={data.calendar}
              onChange={(e) => set("calendar", e.target.value)}>
              {CALENDARS.map(c => (
                <option key={c.id} value={c.id}>{c.label}</option>
              ))}
            </select>
          </div>
        </Field>
      </div>

      <div className="row" style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Email reminder" hint="send an email 24 hours before">
          <div className={"flag-row " + (data.emailReminder ? "on-accent" : "")}>
            <span className="flag-icon">
              <Icon.bell />
            </span>
            <div className="flag-text">
              {data.emailReminder ? (
                <><b>Email 24 hours before</b><span>Sent to {data.email || "the customer email on file"}</span></>
              ) : (
                <><b>No email reminder</b><span>Customer will not receive an automated reminder</span></>
              )}
            </div>
            <div className="segmented">
              <button type="button"
                aria-pressed={data.emailReminder === true}
                onClick={() => { set("emailReminder", true); set("reminders", [1440]); }}>Yes</button>
              <button type="button"
                aria-pressed={data.emailReminder === false}
                onClick={() => { set("emailReminder", false); set("reminders", []); }}>No</button>
            </div>
          </div>
        </Field>
      </div>

      <hr className="hr" />

      {/* ── Notes & attachments ────────────────── */}
      <div className="section-row">
        <span className="section-label">Notes &amp; files</span>
        <span className="section-step">iv.</span>
      </div>

      <Field label="Description / notes">
        <textarea className="textarea"
          placeholder="Crew notes, scope of work, materials needed, gate code…"
          value={data.notes}
          onChange={(e) => set("notes", e.target.value)} />
      </Field>

      <div style={{ marginTop: "var(--gap-row)" }}>
        <Field label="Attachments">
          <div
            className={"dropzone " + (dragOver ? "is-over" : "")}
            onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
            onDragLeave={() => setDragOver(false)}
            onDrop={(e) => {
              e.preventDefault(); setDragOver(false);
              addFiles(e.dataTransfer.files);
            }}
            onClick={() => fileRef.current?.click()}>
            <Icon.upload />
            <div style={{ marginTop: 6 }}>
              <strong>Drop files here</strong> or click to browse
            </div>
            <div style={{ fontSize: 12, marginTop: 4 }}>contracts, photos, audit reports — up to 25 MB each</div>
            <input ref={fileRef} type="file" multiple style={{ display: "none" }}
              onChange={(e) => { addFiles(e.target.files); e.target.value = ""; }} />
          </div>
          {(data.files || []).length > 0 && (
            <div className="file-list">
              {data.files.map(f => (
                <div className="file-row" key={f.id}>
                  <Icon.doc />
                  <span className="fname">{f.name}</span>
                  <span className="fsize">{(f.size/1024).toFixed(0)} KB</span>
                  <button className="frm" type="button"
                    onClick={() => set("files", data.files.filter(x => x.id !== f.id))}>
                    <Icon.x />
                  </button>
                </div>
              ))}
            </div>
          )}
        </Field>
      </div>

      {/* ── Submit ─────────────────────────────── */}
      <div className="submit-row">
        <div className="save-meta">
          <Icon.spark /> Auto-saved · last edit {new Date().toLocaleTimeString([], {hour:"numeric", minute:"2-digit"})}
        </div>
        <button type="submit" className="btn-primary" disabled={!valid}>
          Add to Google Calendar
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12h14M13 6l6 6-6 6"></path>
          </svg>
        </button>
      </div>
    </form>
  );
}

Object.assign(window, {
  EntryForm, Icon, FUEL_TYPES, CALENDARS, EVENT_COLORS,
  fmtDateLong, fmtTime, durationLabel, endTime,
});
