/* Kings Roofing — shared UI components */
(function () {
  const { useState, useRef, useEffect } = React;

  /* ---------- icons ---------- */
  const I = {
    pin: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <path d="M12 21s7-5.5 7-11a7 7 0 1 0-14 0c0 5.5 7 11 7 11Z" />
        <circle cx="12" cy="10" r="2.5" />
      </svg>
    ),
    image: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <rect x="3" y="4" width="18" height="16" rx="2" />
        <circle cx="9" cy="10" r="1.6" />
        <path d="m4 18 5-5 4 4 3-3 4 4" />
      </svg>
    ),
    upload: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <path d="M12 16V4m0 0 4 4m-4-4-4 4" />
        <path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
      </svg>
    ),
    lock: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <rect x="5" y="11" width="14" height="9" rx="2" />
        <path d="M8 11V8a4 4 0 0 1 8 0v3" />
      </svg>
    ),
    check: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="3"
        {...p}
      >
        <path d="m5 12 5 5 9-10" />
      </svg>
    ),
    star: (p) => (
      <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
        <path d="m12 2 2.9 6.3 6.9.7-5.1 4.6 1.4 6.8L12 17.8 5.9 20.4l1.4-6.8L2.2 9l6.9-.7L12 2Z" />
      </svg>
    ),
    award: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <circle cx="12" cy="9" r="6" />
        <path d="m8.5 14-1.5 7 5-3 5 3-1.5-7" />
      </svg>
    ),
    shield: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <path d="M12 3 5 6v5c0 4.5 3 8 7 10 4-2 7-5.5 7-10V6l-7-3Z" />
        <path d="m9 12 2 2 4-4" />
      </svg>
    ),
    phone: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <path d="M5 4h3l2 5-2.5 1.5a11 11 0 0 0 5 5L17 13l5 2v3a2 2 0 0 1-2 2A16 16 0 0 1 4 6a2 2 0 0 1 2-2" />
      </svg>
    ),
    arrow: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2.4"
        {...p}
      >
        <path d="M5 12h14m-6-6 6 6-6 6" />
      </svg>
    ),
    back: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2.4"
        {...p}
      >
        <path d="M19 12H5m6 6-6-6 6-6" />
      </svg>
    ),
    chevron: (p) => (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        {...p}
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    ),
  };

  const Stars = () => (
    <span className="stars">
      {[0, 1, 2, 3, 4].map((i) => (
        <I.star key={i} width="13" height="13" />
      ))}
    </span>
  );

  /* ---------- top bar ---------- */
  function TopBar({ phone }) {
    return (
      <header className="topbar">
        <div className="app topbar-inner">
          <div className="brand">
            <img src="assets/kings-logo-light.png" alt="Kings Roofing" />
            <span className="est">EST. 2014</span>
          </div>
          <nav className="topnav">
            <a href="#">Services</a>
            <a href="#">Projects</a>
            <a href="#">About</a>
            <a href="#" style={{ color: "var(--accent-2)" }}>
              Roof Generator
            </a>
          </nav>
          <div style={{ display: "flex", alignItems: "center", gap: "22px" }}>
            <div className="callbox">
              <span className="dot"></span>
              <div>
                <div className="label">Call us now</div>
                <div className="num">{phone}</div>
              </div>
            </div>
            <button className="btn btn-primary">
              Get a quote
              <span className="arrow">
                <I.arrow width="13" height="13" />
              </span>
            </button>
          </div>
        </div>
      </header>
    );
  }

  /* ---------- steps ---------- */
  function Steps({ step }) {
    // step: 1 = address & colour, 2 = your new roof
    const s2done = step > 2;
    return (
      <div className="steps">
        <div className="app" style={{ display: "flex", padding: "0 28px" }}>
          <div className={"step " + (step === 1 ? "active" : "done")}>
            <div className="step-num">
              {step > 1 ? <I.check width="14" height="14" /> : "1"}
            </div>
            <div className="step-meta">
              <div className="k">Step 1 of 2</div>
              <div className="v">Address &amp; colour</div>
            </div>
          </div>
          <div className={"step " + (step >= 2 ? "active" : "")}>
            <div className="step-num">
              {s2done ? <I.check width="14" height="14" /> : "2"}
            </div>
            <div className="step-meta">
              <div className="k">Step 2 of 2</div>
              <div className="v">Your new roof</div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ---------- trust ---------- */
  function TrustBar() {
    return (
      <div className="trust">
        <div className="trust-item">
          <div className="trust-ic">
            <I.award width="20" height="20" />
          </div>
          <div className="trust-tx">
            <div className="t">#1 Rated Roofer 2025</div>
            <div className="s">Wellington Region</div>
          </div>
        </div>
        <div className="trust-item">
          <div
            className="trust-ic"
            style={{ color: "var(--gold)", width: "auto" }}
          >
            <Stars />
          </div>
          <div className="trust-tx">
            <div className="t">5.0 from 100+ reviews</div>
            <div className="s">Rated on Google</div>
          </div>
        </div>
        <div className="trust-item">
          <div className="trust-ic">
            <I.shield width="20" height="20" />
          </div>
          <div className="trust-tx">
            <div className="t">RANZ Member</div>
            <div className="s">Roofing Association NZ</div>
          </div>
        </div>
      </div>
    );
  }

  /* ---------- address input ---------- */
  function AddressInput({ value, onChange, onPick }) {
    const D = window.KINGS_DATA;
    const [open, setOpen] = useState(false);
    const [matches, setMatches] = useState(D.ADDRESSES.slice(0, 4));
    // Debounced backend lookup (Google Places); falls back to the local list.
    useEffect(() => {
      const q = (value || "").trim();
      const local =
        q.length > 1
          ? D.ADDRESSES.filter((a) =>
              a.toLowerCase().includes(q.toLowerCase()),
            ).slice(0, 4)
          : D.ADDRESSES.slice(0, 4);
      if (q.length < 3) {
        setMatches(local);
        return;
      }
      let alive = true;
      const t = setTimeout(async () => {
        try {
          const res = await fetch(
            "/api/autocomplete?q=" + encodeURIComponent(q),
          );
          const data = await res.json();
          if (!alive) return;
          const list = (data.suggestions || [])
            .map((s) => s.description)
            .filter(Boolean)
            .slice(0, 5);
          setMatches(list.length ? list : local);
        } catch (e) {
          if (alive) setMatches(local);
        }
      }, 220);
      return () => {
        alive = false;
        clearTimeout(t);
      };
    }, [value]);
    return (
      <div className="field">
        <div className="input-wrap">
          <span className="ic">
            <I.pin width="19" height="19" />
          </span>
          <input
            value={value}
            placeholder="Start typing your address…"
            onChange={(e) => {
              onChange(e.target.value);
              setOpen(true);
            }}
            onFocus={() => setOpen(true)}
            onBlur={() => setTimeout(() => setOpen(false), 160)}
          />
          {open && matches.length > 0 && (
            <div className="suggest">
              {matches.map((a) => (
                <button
                  key={a}
                  onMouseDown={() => {
                    onPick(a);
                    setOpen(false);
                  }}
                >
                  <span className="pin">
                    <I.pin width="16" height="16" />
                  </span>
                  {a}
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="field-hint">
          We pull a Street View of your place automatically. Can’t see the roof
          from the road? Upload a photo instead.
        </div>
      </div>
    );
  }

  /* ---------- upload input ---------- */
  function UploadInput({ photo, onUseDemo, onClear }) {
    const [drag, setDrag] = useState(false);
    const [err, setErr] = useState("");
    const inputRef = useRef(null);
    if (photo) {
      return (
        <div className="thumb-pick">
          <img src={photo.src} alt="" />
          <div className="tx">
            <div className="t">{photo.name}</div>
            <div className="s">Ready to render</div>
          </div>
          <button className="x" onClick={onClear} aria-label="Remove">
            ✕
          </button>
        </div>
      );
    }
    const handleFile = (file) => {
      if (!file) return;
      if (!/^image\//.test(file.type)) {
        setErr("That doesn’t look like an image — try a JPG or PNG.");
        return;
      }
      if (file.size > 12 * 1024 * 1024) {
        setErr("That file’s over 12 MB — please pick a smaller photo.");
        return;
      }
      setErr("");
      const url = URL.createObjectURL(file);
      onUseDemo({ src: url, name: file.name, custom: true, file });
    };
    return (
      <div>
        <div
          className={"dropzone" + (drag ? " drag" : "")}
          onDragOver={(e) => {
            e.preventDefault();
            setDrag(true);
          }}
          onDragLeave={() => setDrag(false)}
          onDrop={(e) => {
            e.preventDefault();
            setDrag(false);
            handleFile(e.dataTransfer.files[0]);
          }}
          onClick={() => inputRef.current.click()}
        >
          <div className="up-ic">
            <I.upload width="20" height="20" />
          </div>
          <h4>Drag a photo of your home here</h4>
          <p>
            or <span className="pick">browse your files</span> — JPG or PNG,
            front-on works best.
          </p>
          <input
            ref={inputRef}
            type="file"
            accept="image/*"
            hidden
            onChange={(e) => handleFile(e.target.files[0])}
          />
        </div>
        {err && (
          <div
            className="field-hint"
            style={{ color: "var(--accent-2)", fontWeight: 600 }}
          >
            {err}
          </div>
        )}
        <div
          className="field-hint"
          style={{ display: "flex", gap: "6px", alignItems: "center" }}
        >
          No photo handy?
          <button
            onClick={() =>
              onUseDemo({
                src: "assets/house.jpg",
                name: "Sample home.jpg",
                custom: false,
              })
            }
            style={{
              color: "var(--accent-2)",
              fontWeight: 700,
              textDecoration: "underline",
            }}
          >
            Use a sample home
          </button>
        </div>
      </div>
    );
  }

  window.KUI = { I, Stars, TopBar, Steps, TrustBar, AddressInput, UploadInput };
})();
