/* Start / Condition / Analyzing screens */
const { useState: useStateF, useEffect: useEffectF, useMemo: useMemoF } = React;

function FlowShell({ step, total, onExit, children }) {
  return (
    <div className="min-h-screen bg-bg">
      <FlowBar step={step} total={total} onExit={onExit}/>
      <main className="max-w-[1040px] mx-auto px-6 md:px-10 py-12 md:py-16">
        {children}
      </main>
    </div>
  );
}

/* Page 2 — Address entry */
function StartPage({ onNext, onExit, state, setState }) {
  const [query, setQuery] = useStateF(state.address || "");
  const [open, setOpen] = useStateF(false);

  const options = [
    "1423 N Oliver St, Wichita, KS 67208",
    "1450 N Oliver St, Wichita, KS 67208",
    "1408 N Armour Ave, Wichita, KS 67208",
    "2117 N Volutsia St, Wichita, KS 67214",
  ];
  const filtered = options.filter(o => o.toLowerCase().includes(query.toLowerCase()));
  const canContinue = options.includes(query.trim());

  return (
    <FlowShell step={1} total={4} onExit={onExit}>
      <motion.div
        initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}
        className="max-w-[640px] mx-auto"
      >
        <Card className="p-8 md:p-10">
          <h1 className="font-display text-[32px] md:text-[40px] leading-[1.1] text-primary">Let's start with your address.</h1>
          <p className="mt-3 text-[15.5px] text-muted leading-relaxed">
            We use it to pull real data about your property and your neighborhood.
          </p>

          <div className="mt-8 relative">
            <Field label="Home address">
              <div className="relative">
                <span className="absolute left-4 top-1/2 -translate-y-1/2 text-muted"><Icon name="map-pin" size={16}/></span>
                <input
                  value={query}
                  onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
                  onFocus={() => setOpen(true)}
                  onBlur={() => setTimeout(() => setOpen(false), 150)}
                  placeholder="Start typing your address…"
                  className="w-full h-12 pl-10 pr-4 rounded-lg bg-white border hairline text-ink placeholder:text-muted focus:border-primary focus:ring-4 focus:ring-primary/10 outline-none transition"
                />
              </div>
            </Field>
            {open && filtered.length > 0 && (
              <div className="absolute left-0 right-0 top-[84px] bg-white rounded-xl border hairline shadow-soft-lg overflow-hidden z-10">
                {filtered.map((opt, i) => (
                  <button
                    key={i}
                    onMouseDown={(e) => e.preventDefault()}
                    onClick={() => { setQuery(opt); setOpen(false); setState({ ...state, address: opt }); }}
                    className="w-full text-left px-4 py-3 flex items-center gap-3 hover:bg-bg transition"
                  >
                    <Icon name="home" size={16} className="text-primary/80"/>
                    <span className="text-[14.5px] text-ink">{opt}</span>
                  </button>
                ))}
              </div>
            )}
            <div className="mt-3 flex items-center gap-2 text-[12.5px] text-muted">
              <Icon name="lock" size={13}/> Private and secure. We never share your address.
            </div>
          </div>

          <div className="mt-8 flex items-center justify-between">
            <a href="#" onClick={(e)=>e.preventDefault()} className="text-[13.5px] text-primary/80 hover:text-primary underline-offset-2 hover:underline">Why do we need this?</a>
            <Button
              size="lg"
              onClick={() => { setState({ ...state, address: query }); onNext(); }}
              disabled={!canContinue}
              className={canContinue ? "" : "opacity-40 pointer-events-none"}
            >
              Continue <Icon name="arrow-right" size={16}/>
            </Button>
          </div>
        </Card>
        <p className="text-center mt-8 text-[12.5px] text-muted">
          Pilot market: Wichita, Kansas
        </p>
      </motion.div>
    </FlowShell>
  );
}

/* Page 3 — Condition form */
function RadioCards({ name, value, onChange, options }) {
  return (
    <div role="radiogroup" aria-label={name} className="grid grid-cols-1 sm:grid-cols-2 gap-3">
      {options.map((o) => {
        const checked = value === o.key;
        return (
          <button
            type="button"
            role="radio"
            aria-checked={checked}
            key={o.key}
            onClick={() => onChange(o.key)}
            className={"text-left rounded-xl border p-4 flex items-start gap-4 transition-all " +
              (checked ? "border-primary bg-primary/[0.03] ring-1 ring-primary/20 " : "hairline bg-white hover:border-primary/40 ")
            }
          >
            <span className={"shrink-0 w-10 h-10 rounded-full inline-flex items-center justify-center " +
              (checked ? "bg-primary text-white" : "bg-primary/5 text-primary")}>
              <Icon name={o.icon} size={18}/>
            </span>
            <span className="flex-1">
              <span className="flex items-center justify-between gap-3">
                <span className="text-[15px] font-medium text-ink">{o.label}</span>
                <span className={"w-4 h-4 rounded-full border " + (checked ? "border-primary bg-primary" : "border-muted/50")}>
                  {checked && <span className="block w-1.5 h-1.5 rounded-full bg-white mx-auto mt-[5px]"/>}
                </span>
              </span>
              <span className="block mt-1 text-[13px] text-muted leading-relaxed">{o.desc}</span>
            </span>
          </button>
        );
      })}
    </div>
  );
}

function ConditionPage({ onNext, onExit, state, setState }) {
  const [overall, setOverall] = useStateF(state.overall || "dated");
  const [kitchen, setKitchen] = useStateF(state.kitchen || "dated");
  const [flooring, setFlooring] = useStateF(state.flooring || "good");
  const [timeline, setTimeline] = useStateF(state.timeline || "1-3mo");
  const [financing, setFinancing] = useStateF(!!state.financing);

  const gradeOpts = [
    { key: "excellent", label: "Excellent", desc: "Move-in ready. Recently updated.", icon: "sparkles" },
    { key: "good",      label: "Good",      desc: "Well cared for, minor signs of wear.", icon: "check-circle-2" },
    { key: "dated",     label: "Dated",     desc: "Functional but older finishes.", icon: "clock" },
    { key: "rough",     label: "Rough",     desc: "Needs meaningful repair work.", icon: "hammer" },
  ];
  const timeOpts = [
    { key: "now",    label: "Right away",    desc: "Within the next few weeks.",   icon: "zap" },
    { key: "1-3mo",  label: "In 1–3 months", desc: "Planning ahead a bit.",        icon: "calendar" },
    { key: "3-6mo",  label: "In 3–6 months", desc: "Longer runway.",               icon: "calendar-range" },
    { key: "maybe",  label: "Just exploring",desc: "Not sure yet, curious.",       icon: "compass" },
  ];

  const photos = [
    { label: "Kitchen.jpg", tint: "warm" },
    { label: "Living room.jpg", tint: "cool" },
    { label: "Exterior.jpg", tint: "default" },
  ];

  return (
    <FlowShell step={2} total={4} onExit={onExit}>
      <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.4 }} className="max-w-[820px] mx-auto">
        <div className="mb-8">
          <h1 className="font-display text-[32px] md:text-[40px] leading-[1.1] text-primary">Tell us about your home.</h1>
          <p className="mt-3 text-[15.5px] text-muted">A few quick questions help us ground the numbers. None of this is shared.</p>
        </div>

        <div className="space-y-10">
          <section>
            <h2 className="font-display text-[22px] text-primary mb-3">How would you describe your home's overall condition?</h2>
            <RadioCards name="overall" value={overall} onChange={setOverall} options={gradeOpts}/>
          </section>

          <section>
            <h2 className="font-display text-[22px] text-primary mb-3">And your kitchen?</h2>
            <RadioCards name="kitchen" value={kitchen} onChange={setKitchen} options={gradeOpts}/>
          </section>

          <section>
            <h2 className="font-display text-[22px] text-primary mb-3">Flooring?</h2>
            <RadioCards name="flooring" value={flooring} onChange={setFlooring} options={gradeOpts}/>
          </section>

          <section>
            <h2 className="font-display text-[22px] text-primary mb-3">When are you thinking of selling?</h2>
            <RadioCards name="timeline" value={timeline} onChange={setTimeline} options={timeOpts}/>
          </section>

          <section>
            <h2 className="font-display text-[22px] text-primary mb-2">Add a few photos</h2>
            <p className="text-[14px] text-muted mb-4">Photos help us give you a more accurate renovation visualization.</p>
            <div className="rounded-xl border-2 border-dashed border-primary/20 bg-white p-6 md:p-8">
              <div className="flex flex-col md:flex-row items-start md:items-center gap-6">
                <div className="flex -space-x-3">
                  {photos.map((p, i) => (
                    <div key={i} className={"w-20 h-16 rounded-lg border-2 border-white shadow-soft overflow-hidden " +
                      (p.tint === "warm" ? "photo-ph-warm" : p.tint === "cool" ? "photo-ph-cool" : "photo-ph")}>
                    </div>
                  ))}
                </div>
                <div className="flex-1">
                  <p className="text-[14.5px] text-ink">Drag photos here, or browse from your device.</p>
                  <p className="text-[12.5px] text-muted mt-1">JPG, PNG, or HEIC up to 20MB each.</p>
                </div>
                <Button variant="outline" size="md">
                  <Icon name="upload" size={16}/> Browse files
                </Button>
              </div>
              <div className="mt-5 pt-5 border-t hairline text-[12.5px] text-muted inline-flex items-center gap-2">
                <Icon name="check-circle-2" size={14} className="text-success"/> 3 photos attached
              </div>
            </div>
          </section>

          <section>
            <label className="flex items-start gap-3 p-4 rounded-xl border hairline bg-white cursor-pointer">
              <input type="checkbox" checked={financing} onChange={(e)=>setFinancing(e.target.checked)}
                className="mt-0.5 w-4 h-4 rounded border-muted accent-[#0F3D3E]"
              />
              <span>
                <span className="text-[14.5px] text-ink">I'd like to hear about renovation financing options.</span>
                <span className="block text-[12.5px] text-muted mt-0.5">Totally optional. We'll only include this if you ask.</span>
              </span>
            </label>
          </section>

          <div className="flex flex-col-reverse md:flex-row md:items-center md:justify-between gap-4 pt-4">
            <a href="#" onClick={(e)=>e.preventDefault()} className="text-[13.5px] text-primary/80 hover:text-primary">Save and finish later →</a>
            <Button size="lg" onClick={() => { setState({ ...state, overall, kitchen, flooring, timeline, financing }); onNext(); }}>
              See my analysis <Icon name="arrow-right" size={16}/>
            </Button>
          </div>
        </div>
      </motion.div>
    </FlowShell>
  );
}

/* Page 4 — Analyzing */
function AnalyzingPage({ onDone, state }) {
  const addr = state.address || "1423 N Oliver St";
  const steps = [
    `Pulling property records for ${addr.split(",")[0]}`,
    "Reviewing 14 comparable sales in your neighborhood",
    "Modeling renovation scenarios",
    "Preparing your personalized analysis",
  ];
  const [progress, setProgress] = useStateF(0);
  useEffectF(() => {
    const delays = [900, 1100, 1400, 1200];
    let i = 0, t;
    const tick = () => {
      i += 1;
      setProgress(i);
      if (i < steps.length) t = setTimeout(tick, delays[i] || 1000);
      else t = setTimeout(onDone, 800);
    };
    t = setTimeout(tick, delays[0]);
    return () => clearTimeout(t);
  }, []);

  return (
    <div className="min-h-screen flex flex-col bg-bg">
      <div className="flex-1 flex items-center justify-center px-6">
        <motion.div
          initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}
          className="text-center max-w-[520px]"
        >
          <div className="relative w-24 h-24 mx-auto mb-8">
            <div className="absolute inset-0 rounded-full border-[3px] border-primary/10"/>
            <motion.div
              animate={{ rotate: 360 }} transition={{ duration: 1.8, ease: "linear", repeat: Infinity }}
              className="absolute inset-0 rounded-full border-[3px] border-transparent border-t-primary border-r-primary/60"
            />
            <motion.div
              animate={{ scale: [1, 1.08, 1], opacity: [0.7, 1, 0.7] }} transition={{ duration: 2, repeat: Infinity }}
              className="absolute inset-4 rounded-full bg-accent/30 flex items-center justify-center text-primary"
            >
              <Icon name="home" size={22}/>
            </motion.div>
          </div>

          <h1 className="font-display text-[28px] md:text-[32px] text-primary leading-tight">Preparing your analysis…</h1>
          <p className="mt-2 text-[14.5px] text-muted">This usually takes about 10 seconds.</p>

          <ul className="mt-10 text-left space-y-3">
            {steps.map((s, i) => {
              const done = i < progress;
              const active = i === progress;
              return (
                <li key={i} className="flex items-start gap-3">
                  <span className={"mt-0.5 w-6 h-6 rounded-full inline-flex items-center justify-center shrink-0 transition-colors " +
                    (done ? "bg-success text-white" : active ? "bg-primary/10 text-primary" : "bg-primary/5 text-muted")}>
                    {done ? <Icon name="check" size={14}/> :
                      active
                        ? <motion.span animate={{ rotate: 360 }} transition={{ duration: 1, ease: "linear", repeat: Infinity }}>
                            <Icon name="loader-2" size={13}/>
                          </motion.span>
                        : <span className="w-1.5 h-1.5 rounded-full bg-muted/50"/>
                    }
                  </span>
                  <span className={"text-[14.5px] " + (done || active ? "text-ink" : "text-muted")}>{s}</span>
                </li>
              );
            })}
          </ul>
        </motion.div>
      </div>
    </div>
  );
}

Object.assign(window, { StartPage, ConditionPage, AnalyzingPage });
