// Main app — auth, routing, state, API wiring.
const { useState: useAS, useEffect: useAE } = React;
const CONFIG = window.CONFIG;

let toastSeq = 0;

function App() {
  const [authed, setAuthed] = useAS(() => !!localStorage.getItem("roa_access_token"));
  const [user,   setUser]   = useAS(() => {
    try { return JSON.parse(localStorage.getItem("roa_user") || "null"); } catch (_) { return null; }
  });
  const [view,             setView]             = useAS("form");
  const [meta,             setMeta]             = useAS(null);
  const [selected,         setSelected]         = useAS(null);
  const [toasts,           setToasts]           = useAS([]);
  const [tableRefreshKey,  setTableRefreshKey]  = useAS(0);

  // Load meta once after login (populates form options + filter dropdowns)
  useAE(() => {
    if (!authed || meta) return;
    window.api.getMeta().then((data) => {
      if (!data) return;
      setMeta(data);
      // Extend STATUS map so StatusBadge can render inbound_status values
      const toneHints = { received: "blue", duplicate: "low" };
      (data.inbound_status || []).forEach((s) => {
        if (!window.ROA_DATA.STATUS[s.id]) {
          window.ROA_DATA.STATUS[s.id] = { tone: toneHints[s.id] || "neutral", label: s.identity };
        }
      });
    }).catch(() => {});
  }, [authed]);

  function toast(title, sub) {
    const id = ++toastSeq;
    setToasts((p) => [...p, { id, title, sub }]);
    setTimeout(() => setToasts((p) => p.filter((x) => x.id !== id)), 3400);
  }

  // Returns {} on success, or { errors: {field: msg} } on validation failure.
  async function submitLead(form) {
    const fullName = [form.firstName, form.lastName].filter(Boolean).join(" ");

    const typeApiMap = { Buy: "Buying", Sell: "Selling", Lease: "Leasing" };
    const pqApiMap   = { Yes: "yes", No: "no", "Not sure": "not_sure" };
    const body = {
      first_name:    form.firstName.trim(),
      phone:         form.phone.replace(/\D/g, ""),
      lead_type:     typeApiMap[form.types[0]] || form.types[0] || "",
      city:          form.city,
      state:         form.state,
      pre_qualified: pqApiMap[form.preQual] || form.preQual || "",
    };
    if (form.lastName?.trim())                            body.last_name            = form.lastName.trim();
    if (form.email)                                       body.email                = form.email;
    if (form.street)                                  body.street_address       = form.street;
    if (form.zip)                                     body.zipcode              = form.zip;
    if (form.timeline)                                body.timeline             = form.timeline;
    if (form.bestTime)                                body.best_time_to_call    = new Date(form.bestTime).toISOString();
    if (form.listingDate && form.types.includes("Sell")) body.desired_listing_date = form.listingDate;
    if (form.cashOffer)                               body.cash_offer           = true;
    if (form.notes)                                   body.background_info      = form.notes;

    try {
      const r = await window.api.submitLead(body);
      if (r?.status === "success") {
        toast("Lead logged", `${fullName} is now in the pipeline.`);
        setTableRefreshKey((k) => k + 1);
        setView("table");
        return {};
      }
      const data = r?.data;
      if (data && typeof data === "object") {
        const fieldMap = {
          first_name: "firstName", last_name: "lastName", phone: "phone", email: "email",
          lead_type: "types", city: "city", state: "state", pre_qualified: "preQual",
          timeline: "timeline", cash_offer: "cashOffer", background_info: "notes",
        };
        const errors = {};
        Object.entries(data).forEach(([k, msgs]) => {
          const fk = fieldMap[k] || k;
          errors[fk] = Array.isArray(msgs) ? msgs[0] : msgs;
        });
        return { errors };
      }
      return { errors: { _general: typeof data === "string" ? data : "Submission failed." } };
    } catch (_) {
      toast("Error", "Failed to submit lead.");
      return { errors: {} };
    }
  }

  // Called by LeadDetail after a note is posted — bumps the open drawer's count.
  function onNoteAdded(leadId) {
    setSelected((s) => s && s.id === leadId ? { ...s, note_count: (s.note_count || 0) + 1 } : s);
  }

  async function handleLogout() {
    await window.api.logout().catch(() => {});
    setAuthed(false); setUser(null); setMeta(null); setSelected(null); setView("form");
  }

  if (!authed) {
    return <Login onLogin={(userData) => { setAuthed(true); setUser(userData); }} />;
  }

  return (
    <div style={{ minHeight: "calc(100vh / 0.8)" }}>
      <Header view={view} onNav={(v) => setView(v)} onLogout={handleLogout} user={user} />
      {view === "form"
        ? <LeadForm onSubmit={submitLead} layout={CONFIG.formLayout} meta={meta} />
        : <TrackingTable
            refreshKey={tableRefreshKey}
            onOpen={(l) => setSelected(l)}
            density={CONFIG.density}
            meta={meta}
            onToast={toast}
          />}
      {selected && (
        <LeadDetail
          lead={selected}
          onClose={() => setSelected(null)}
          onNoteAdded={onNoteAdded}
        />
      )}
      <ToastHost toasts={toasts} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
