// EzClaim — shared UI primitives.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

function Button({ kind = "primary", size = "", block = false, icon, iconRight, children, className = "", ...rest }) {
  const cls = [
    "btn",
    `btn-${kind}`,
    size === "lg" ? "btn-lg" : size === "sm" ? "btn-sm" : "",
    block ? "btn-block" : "",
    className,
  ].filter(Boolean).join(" ");
  return (
    <button className={cls} {...rest}>
      {icon ? <span className="btn-icon-l">{icon}</span> : null}
      {children}
      {iconRight ? <span className="btn-icon-r">{iconRight}</span> : null}
    </button>
  );
}

function Field({ label, hint, help, error, children, htmlFor }) {
  return (
    <div className="field">
      {label ? (
        <label htmlFor={htmlFor} className="field-label">
          <span>{label}</span>
          {hint ? <span className="hint">{hint}</span> : null}
        </label>
      ) : null}
      {children}
      {error ? (
        <div className="field-err"><I.Alert size={14}/> {error}</div>
      ) : help ? (
        <div className="field-help">{help}</div>
      ) : null}
    </div>
  );
}

function Input({ leftIcon, size = "", className = "", ...rest }) {
  const cls = ["input", size === "lg" ? "input-lg" : "", className].filter(Boolean).join(" ");
  if (leftIcon) {
    return (
      <div className={"input-affix" + (size === "lg" ? " lg" : "")}>
        <span className="affix">{leftIcon}</span>
        <input className={cls} {...rest} />
      </div>
    );
  }
  return <input className={cls} {...rest} />;
}

function Tag({ children, kind = "" }) {
  const cls = "tag" + (kind ? " tag-" + kind : "");
  return <span className={cls}>{children}</span>;
}

function Callout({ kind = "", icon, title, children }) {
  const ic = icon ?? (kind === "warn" ? <I.Alert size={18}/> : kind === "err" ? <I.Alert size={18}/> : kind === "good" ? <I.CheckCircle size={18}/> : <I.Info size={18}/>);
  return (
    <div className={"callout" + (kind ? " " + kind : "")}>
      <span className="ci">{ic}</span>
      <div>
        {title ? <div style={{ fontWeight: 600, marginBottom: 2, color: "var(--ink-900)" }}>{title}</div> : null}
        <div>{children}</div>
      </div>
    </div>
  );
}

function RadioCard({ selected, onClick, title, sub, children, right }) {
  return (
    <button type="button" className={"radio-card" + (selected ? " selected" : "")} onClick={onClick}>
      <span className="dot" />
      <div className="rc-body">
        <div className="rc-title">{title}</div>
        {sub ? <div className="rc-sub">{sub}</div> : null}
        {children}
      </div>
      {right ? <div>{right}</div> : null}
    </button>
  );
}

function Checkbox({ checked, onChange, label, sub, id }) {
  function toggle(e) {
    e.preventDefault();
    onChange(!checked);
  }
  function onKeyDown(e) {
    if (e.key === " " || e.key === "Enter") toggle(e);
  }
  return (
    <label
      htmlFor={id}
      role="checkbox"
      aria-checked={checked}
      tabIndex={0}
      onClick={toggle}
      onKeyDown={onKeyDown}
      style={{ display: "flex", gap: 10, alignItems: "flex-start", cursor: "pointer", padding: "8px 0" }}
    >
      <span className={"cb" + (checked ? " on" : "")} aria-hidden="true" />
      <span style={{ flex: 1 }}>
        <span style={{ fontSize: 14.5, color: "var(--ink-900)", fontWeight: 500 }}>{label}</span>
        {sub ? <div className="subtle" style={{ marginTop: 2 }}>{sub}</div> : null}
      </span>
    </label>
  );
}

function Switch({ on, onChange, label, sub }) {
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start", padding: "10px 0" }}>
      <span className={"switch" + (on ? " on" : "")} onClick={() => onChange(!on)} role="switch" aria-checked={on}/>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14.5, color: "var(--ink-900)", fontWeight: 500 }}>{label}</div>
        {sub ? <div className="subtle" style={{ marginTop: 2 }}>{sub}</div> : null}
      </div>
    </div>
  );
}

function WizardBar({ step, total, label }) {
  const cells = [];
  for (let i = 1; i <= total; i++) {
    cells.push(<i key={i} className={i < step ? "done" : i === step ? "cur" : ""}/>);
  }
  return (
    <div>
      <div className="wiz-meta">
        <span className="step">Step {step} of {total}</span>
        <span className="muted">{label}</span>
      </div>
      <div className="wiz-bar">{cells}</div>
    </div>
  );
}

function PropertyCard({ p, compact = false, right }) {
  if (!p) return null;
  const status = EZ_MOCK.homesteadStatus(p);
  const owner = p.public_prefill?.owner_name || [p.public_prefill?.owner_name_1, p.public_prefill?.owner_name_2].filter(Boolean).join(" & ") || "—";
  const jurisdiction = p.county || "Maryland";
  const parcel = p.parcel_id || p.property_id || "Pending";
  return (
    <div className="property-card">
      <div className="pc-hd">
        <div className="pc-icon"><I.Home size={20}/></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="pc-addr">{p.site_address}</div>
          <div className="pc-sub">{jurisdiction} · Parcel {parcel}</div>
        </div>
        {right ?? null}
      </div>
      {!compact ? (
        <div className="pc-body">
          <div className="kv"><span className="k">Owner of record</span><span className="v">{owner}</span></div>
          <div className="kv"><span className="k">Assessment year</span><span className="v tabnum">{p.assessment_year}</span></div>
          <div className="kv"><span className="k">Current assessed value</span><span className="v tabnum">{EZ_MOCK.fmtUSD(p.current_assessed_value)}</span></div>
          <div className="kv"><span className="k">Previous</span><span className="v tabnum">{EZ_MOCK.fmtUSD(p.previous_assessed_value)}</span></div>
          <div className="kv"><span className="k">Homestead status</span>
            <span className="v">
              <Tag kind={status.kind}>
                {status.icon === "check" ? <I.Check size={11}/> : <span className="dot"/>}
                {status.label}
              </Tag>
            </span>
          </div>
        </div>
      ) : null}
    </div>
  );
}

// Simple hash router
function useHashRoute() {
  const get = () => (window.location.hash || "#/").replace(/^#/, "");
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const f = () => setRoute(get());
    window.addEventListener("hashchange", f);
    return () => window.removeEventListener("hashchange", f);
  }, []);
  const nav = useCallback((to) => { window.location.hash = "#" + to; }, []);
  // Parse /a/b/c -> ['a','b','c']
  const segs = route.split("/").filter(Boolean);
  return { route, segs, nav };
}

// Small persistent state via session storage
function useSessionState(key, initial) {
  const [v, setV] = useState(() => {
    try {
      const raw = sessionStorage.getItem(key);
      if (raw != null) return JSON.parse(raw);
    } catch (e) {}
    return initial;
  });
  useEffect(() => {
    try { sessionStorage.setItem(key, JSON.stringify(v)); } catch (e) {}
  }, [key, v]);
  return [v, setV];
}

Object.assign(window, { Button, Field, Input, Tag, Callout, RadioCard, Checkbox, Switch, WizardBar, PropertyCard, useHashRoute, useSessionState });
