/* global React, Icon, Button, Eyebrow, nav, BAFrame */
/* Patch Me Up — Photo-first estimate flow */
const { useState: useStateE, useEffect: useEffectE } = React;

const REPAIR_TYPES = [
  { k: "post-trade",   icon: "plumbing",       t: "Post‑trade repair",  d: "After a plumber, HVAC, or electrician opened the wall." },
  { k: "ceiling",      icon: "ceiling-repair", t: "Ceiling repair",     d: "Access cuts, leak aftermath, popcorn / knockdown match." },
  { k: "patch",        icon: "wall-repair",    t: "Patch + texture + paint", d: "Holes, dents, cracks, failed DIY patches." },
  { k: "pre-listing",  icon: "listing",        t: "Pre‑listing repair", d: "Multiple areas, finished before photos or showings." },
  { k: "rental-turn",  icon: "key",            t: "Rental / unit turn", d: "Move‑out, tenant damage, short‑term rental between guests." },
  { k: "multi",        icon: "before-after",   t: "Several small repairs", d: "Bundle them into a single visit." },
];

const TIMING_OPTIONS = [
  { k: "deadline", t: "I have a deadline", d: "Photos, move‑in, inspection, check‑in." },
  { k: "asap",     t: "As soon as possible", d: "Earliest available technician." },
  { k: "week",     t: "Within a week",    d: "Standard small‑repair scheduling." },
  { k: "flex",     t: "I'm flexible",     d: "Best price &amp; routing." },
];

const AUDIENCE_OPTIONS = [
  { k: "homeowner",    t: "Homeowner" },
  { k: "trade",        t: "Trade partner" },
  { k: "realtor",      t: "Realtor / seller" },
  { k: "pm",           t: "Property manager" },
  { k: "str",          t: "Short‑term rental" },
  { k: "other",        t: "Other" },
];

function StepRail({ current, total }) {
  return (
    <div className="estimate-rail" aria-label={`Step ${current + 1} of ${total}`}>
      {Array.from({ length: total }).map((_, i) => (
        <div
          key={i}
          className={"bar" + (i < current ? " is-done" : i === current ? " is-active" : "")}
        />
      ))}
    </div>
  );
}

function StepHeader({ idx, total, label, q, help }) {
  return (
    <div>
      <StepRail current={idx} total={total} />
      <div className="estimate-step-label">Step {idx + 1} of {total}</div>
      <h1 className="estimate-q">{q}</h1>
      {help && <p className="estimate-help" dangerouslySetInnerHTML={{ __html: help }} />}
    </div>
  );
}

function OptionCard({ icon, title, desc, selected, onClick }) {
  return (
    <button
      type="button"
      className={"option-card" + (selected ? " is-selected" : "")}
      onClick={onClick}
    >
      <span className="radio">
        {selected && <Icon name="check" size={14} />}
      </span>
      <span>
        <span className="ttl">{title}</span>
        {desc && <span className="desc" dangerouslySetInnerHTML={{ __html: desc }} />}
      </span>
      {icon && <span className="icoslot"><Icon name={icon} size={22} /></span>}
    </button>
  );
}

/* ─────────── Step 1: What needs repair? ─────────── */
function Step1({ state, set, onNext }) {
  return (
    <div>
      <StepHeader idx={0} total={5}
        q="What needs repair?"
        help="Pick the closest match. You can add details in a moment — this just routes your photos to the right team."
      />
      <div className="option-list">
        {REPAIR_TYPES.map(r => (
          <OptionCard
            key={r.k}
            icon={r.icon}
            title={r.t}
            desc={r.d}
            selected={state.repairType === r.k}
            onClick={() => set({ repairType: r.k })}
          />
        ))}
      </div>
      <div className="estimate-actions">
        <div className="left t-proof">Takes about 2 minutes</div>
        <Button kind="primary" size="lg" onClick={onNext} disabled={!state.repairType}>
          Continue <Icon name="arrow-right" size={18} />
        </Button>
      </div>
    </div>
  );
}

/* ─────────── Step 2: Upload photos ─────────── */
function Step2({ state, set, onNext, onBack }) {
  const photos = state.photos || [];
  const addPhoto = () => set({ photos: [...photos, "ds/photo-before.svg"] });
  const removePhoto = (i) => set({ photos: photos.filter((_, idx) => idx !== i) });

  return (
    <div>
      <StepHeader idx={1} total={5}
        q="Upload a few photos."
        help="A wide shot plus a close‑up is best. Include something for scale — a hand, a credit card, or a ruler — so we can size the patch."
      />
      <div className="photo-grid">
        {photos.map((p, i) => (
          <div key={i} className="photo-tile">
            <img src={p} alt="" />
            <span className="num">{String(i + 1).padStart(2, "0")}</span>
            <button className="x" aria-label="Remove" onClick={() => removePhoto(i)}>
              <Icon name="x" size={14} />
            </button>
          </div>
        ))}
        <button className="photo-add" type="button" onClick={addPhoto}>
          <Icon name="camera" size={28} />
          <span>{photos.length === 0 ? "Add photos" : "Add more"}</span>
        </button>
      </div>

      <div className="tip-callout" style={{ marginTop: 18 }}>
        <span className="ico"><Icon name="sparkle" size={18} /></span>
        <span>
          <b>No photos handy?</b> You can still continue — we'll text you a link to upload them in 30 seconds.
        </span>
      </div>

      <div style={{ marginTop: 20 }}>
        <label className="field-label">Anything we should know?</label>
        <textarea
          className="textarea"
          rows="3"
          placeholder="Optional. e.g., 'plumber cut a 14-inch hole in the kitchen ceiling above the sink, knockdown texture.'"
          value={state.notes || ""}
          onChange={(e) => set({ notes: e.target.value })}
        />
      </div>

      <div className="estimate-actions">
        <Button kind="ghost" onClick={onBack}>← Back</Button>
        <div className="left"></div>
        <Button kind="primary" size="lg" onClick={onNext}>
          Continue <Icon name="arrow-right" size={18} />
        </Button>
      </div>
    </div>
  );
}

/* ─────────── Step 3: Where is the property? ─────────── */
function Step3({ state, set, onNext, onBack }) {
  return (
    <div>
      <StepHeader idx={2} total={5}
        q="Where is the property?"
        help="We serve the Phoenix Metro: Phoenix, Scottsdale, Tempe, Mesa, Chandler, Gilbert, and Glendale."
      />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div className="full" style={{ gridColumn: "1 / -1" }}>
          <label className="field-label">ZIP code <span style={{ color: "var(--pmu-clay)" }}>•</span></label>
          <input
            className="input"
            placeholder="e.g., 85016"
            value={state.zip || ""}
            onChange={(e) => set({ zip: e.target.value })}
            maxLength={5}
            inputMode="numeric"
          />
          <div className="field-hint">We confirm coverage on submission. Outside metro? We'll help you find a local pro.</div>
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <label className="field-label">Street address <span style={{ color: "var(--fg-subtle)" }}>(optional)</span></label>
          <input
            className="input"
            placeholder="So the tech can plan parking + access"
            value={state.address || ""}
            onChange={(e) => set({ address: e.target.value })}
          />
        </div>
        <div>
          <label className="field-label">Who's booking?</label>
          <select className="select" value={state.audience || "homeowner"} onChange={(e) => set({ audience: e.target.value })}>
            {AUDIENCE_OPTIONS.map(a => <option key={a.k} value={a.k}>{a.t}</option>)}
          </select>
        </div>
        <div>
          <label className="field-label">Property type</label>
          <select className="select" value={state.propertyType || "single"} onChange={(e) => set({ propertyType: e.target.value })}>
            <option value="single">Single‑family home</option>
            <option value="condo">Condo / townhome</option>
            <option value="rental">Rental unit</option>
            <option value="str">Short‑term rental</option>
            <option value="commercial">Light commercial</option>
          </select>
        </div>
      </div>

      <div className="estimate-actions">
        <Button kind="ghost" onClick={onBack}>← Back</Button>
        <div className="left"></div>
        <Button kind="primary" size="lg" onClick={onNext} disabled={!(state.zip && state.zip.length === 5)}>
          Continue <Icon name="arrow-right" size={18} />
        </Button>
      </div>
    </div>
  );
}

/* ─────────── Step 4: Deadline? ─────────── */
function Step4({ state, set, onNext, onBack }) {
  return (
    <div>
      <StepHeader idx={3} total={5}
        q="When does it need to be done?"
        help="If you have a hard deadline — listing photos, move‑in, check‑in — we'll build the schedule backward from your date."
      />
      <div className="option-list">
        {TIMING_OPTIONS.map(o => (
          <OptionCard
            key={o.k}
            title={o.t}
            desc={o.d}
            selected={state.timing === o.k}
            onClick={() => set({ timing: o.k })}
          />
        ))}
      </div>

      {state.timing === "deadline" && (
        <div style={{ marginTop: 16 }}>
          <label className="field-label">Deadline (must be done by)</label>
          <input
            type="text"
            className="input"
            placeholder="e.g., Friday May 30, 9:00 AM"
            value={state.deadline || ""}
            onChange={(e) => set({ deadline: e.target.value })}
          />
          <div className="field-hint">We schedule with at least a 24‑hour buffer where possible.</div>
        </div>
      )}

      <div className="estimate-actions">
        <Button kind="ghost" onClick={onBack}>← Back</Button>
        <div className="left"></div>
        <Button kind="primary" size="lg" onClick={onNext} disabled={!state.timing}>
          Continue <Icon name="arrow-right" size={18} />
        </Button>
      </div>
    </div>
  );
}

/* ─────────── Step 5: Contact + consent ─────────── */
function Step5({ state, set, onNext, onBack }) {
  return (
    <div>
      <StepHeader idx={4} total={5}
        q="Where should we send the estimate?"
        help="We follow up by text first — most replies are within 5 minutes during business hours. We never share your info."
      />
      <div className="referral-form">
        <div>
          <label className="field-label">Your name</label>
          <input className="input" value={state.name || ""} onChange={(e) => set({ name: e.target.value })} placeholder="Jane Reyes" />
        </div>
        <div>
          <label className="field-label">Mobile</label>
          <input className="input" value={state.phone || ""} onChange={(e) => set({ phone: e.target.value })} placeholder="(602) 555‑0148" inputMode="tel" />
        </div>
        <div className="full">
          <label className="field-label">Email <span style={{ color: "var(--fg-subtle)" }}>(optional, for the proof report)</span></label>
          <input className="input" type="email" value={state.email || ""} onChange={(e) => set({ email: e.target.value })} placeholder="jane@example.com" />
        </div>
        <div className="full">
          <label className="field-label">Referral source <span style={{ color: "var(--fg-subtle)" }}>(optional)</span></label>
          <input className="input" value={state.source || ""} onChange={(e) => set({ source: e.target.value })} placeholder="Plumber, realtor, Google, Nextdoor…" />
        </div>
        <label className="full" style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 4, cursor: "pointer" }}>
          <input
            type="checkbox"
            checked={state.smsOk !== false}
            onChange={(e) => set({ smsOk: e.target.checked })}
            style={{ marginTop: 4, width: 18, height: 18, accentColor: "var(--pmu-teal)" }}
          />
          <span style={{ fontSize: 14, color: "var(--fg-muted)", lineHeight: 1.5 }}>
            It's okay to text me about this repair. Standard message rates apply. We won't send marketing texts.
          </span>
        </label>
      </div>

      <div className="tip-callout" style={{ marginTop: 18 }}>
        <span className="ico"><Icon name="clock" size={18} /></span>
        <span>
          <b>A real person texts you back within 5 minutes</b> during business hours (Mon–Sat · 7a–7p). Not a chatbot, not a queue.
        </span>
      </div>

      <div className="estimate-actions">
        <Button kind="ghost" onClick={onBack}>← Back</Button>
        <div className="left"></div>
        <Button
          kind="action"
          size="lg"
          onClick={onNext}
          disabled={!(state.name && state.phone)}
        >
          <Icon name="camera" size={18} />
          Send my repair request
        </Button>
      </div>
    </div>
  );
}

/* ─────────── Confirmation screen ─────────── */
function Confirm({ state }) {
  return (
    <div>
      <div className="confirm-hero">
        <div className="confirm-check"><Icon name="check" size={32} /></div>
        <h1 className="estimate-q" style={{ marginBottom: 8 }}>Got it. We're on it.</h1>
        <p className="estimate-help" style={{ maxWidth: 460, margin: "0 auto" }}>
          A real Patch Me Up team member is reviewing your photos right now. You'll hear back by text in under 5 minutes during business hours.
        </p>
      </div>

      <div style={{ display: "flex", gap: 8, justifyContent: "center", marginBottom: 24, flexWrap: "wrap" }}>
        <span className="badge badge-info"><span className="dot"></span>#{Math.floor(Math.random() * 9000 + 1000)}</span>
        <span className="badge badge-proof"><span className="dot"></span>{state.repairType || "Repair"} · {state.timing || "Scheduled"}</span>
      </div>

      <div className="timeline">
        {[
          { ts: "Just now",     t: "Repair request received",        done: true },
          { ts: "≤ 5 min",      t: "Team reviews photos, texts back" },
          { ts: "Same day",     t: "Scoped estimate + price range" },
          { ts: "1–3 days",     t: "Technician on‑site, repair complete" },
          { ts: "Same day",     t: "Before/after proof report sent" },
        ].map((row, i) => (
          <div key={i} className={"timeline-row" + (row.done ? " is-done" : "")}>
            <span className="ts">{row.ts}</span>
            <span className="lbl">{row.t}</span>
            <span className="ico-end">
              <Icon name={row.done ? "check-circle" : "clock"} size={18} />
            </span>
          </div>
        ))}
      </div>

      <div className="tip-callout" style={{ marginTop: 22 }}>
        <span className="ico"><Icon name="chat" size={18} /></span>
        <span>
          <b>Reply to our text with any extra detail</b> — a deadline, an access note (lockbox, code, pet), or more photos. It speeds the estimate up.
        </span>
      </div>

      <div className="estimate-actions" style={{ justifyContent: "center" }}>
        <Button kind="secondary" to="/proof">See proof gallery</Button>
        <Button kind="primary" to="/">Back to home <Icon name="arrow-right" size={16} /></Button>
      </div>
    </div>
  );
}

/* ─────────── Container ─────────── */
function EstimatePage() {
  const [step, setStep] = useStateE(0);
  const [state, setState] = useStateE({
    repairType: "post-trade",
    photos: ["ds/photo-before.svg", "ds/photo-before.svg"],
    timing: "week",
    audience: "homeowner",
    propertyType: "single",
    smsOk: true,
  });
  const set = (partial) => setState(s => ({ ...s, ...partial }));
  const next = () => setStep(s => Math.min(s + 1, 5));
  const back = () => setStep(s => Math.max(s - 1, 0));

  useEffectE(() => { window.scrollTo({ top: 0, behavior: "smooth" }); }, [step]);

  const stepsMap = {
    0: <Step1 state={state} set={set} onNext={next} />,
    1: <Step2 state={state} set={set} onNext={next} onBack={back} />,
    2: <Step3 state={state} set={set} onNext={next} onBack={back} />,
    3: <Step4 state={state} set={set} onNext={next} onBack={back} />,
    4: <Step5 state={state} set={set} onNext={next} onBack={back} />,
    5: <Confirm state={state} />,
  };

  return (
    <div className="estimate-page">
      <div className="container-narrow" style={{ marginBottom: 24 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
          <Eyebrow icon="camera">Photo‑first estimate</Eyebrow>
          <a href="tel:6025550148" style={{ fontFamily: "var(--font-display)", fontWeight: 700, color: "var(--pmu-teal)", fontSize: 14 }}>
            Or call (602) 555‑0148
          </a>
        </div>
      </div>
      <div className="estimate-shell">
        {stepsMap[step]}
      </div>
    </div>
  );
}

Object.assign(window, { EstimatePage });
