/* global React, ReactDOM, ToastHost, LoginScreen, Dashboard, ProjectsScreen, ContractsScreen, HousesScreen, ReportsScreen, SettingsScreen, Sidebar, TopNav, Crumb, TweaksPanel, useTweaks, TweakRadio, TweakSection, PaymentsScreen */
const { useState, useEffect } = React;

// Empty shell while Firebase boots
const EMPTY_DATA = { user:{email:"",name:"",role:""}, projects:[], contracts:{}, houses:{}, payments:{}, activity:[] };

function App() {
  const [fbState, setFbState] = useState(() => window.FB ? window.FB.state : { user:null, projects:[], contracts:{}, houses:{}, payments:{} });
  const [route, setRoute] = useState({ screen: "dashboard" });
  const [selectedProjectId, setSelectedProjectId] = useState(null);

  // Subscribe to Firebase reactive store
  useEffect(() => {
    const tryAttach = () => {
      if (window.FB) {
        const off = window.FB.subscribe((s) => setFbState({ ...s }));
        return off;
      }
      const t = setTimeout(tryAttach, 80);
      return () => clearTimeout(t);
    };
    return tryAttach();
  }, []);

  // Adapt FB state to legacy data shape consumed by screens
  const data = {
    user: fbState.user ? { email: fbState.user.email, name: fbState.user.name, role: "ผู้ใช้" } : EMPTY_DATA.user,
    projects: (fbState.projects || []).map((p) => ({
      ...p,
      value_total: p.value_total || 0,
      paid_total: p.paid_total || 0,
      contract_count: (fbState.contracts?.[p.id] || []).length,
      house_count: (fbState.contracts?.[p.id] || []).reduce((s, c) => s + ((fbState.houses?.[c.id] || []).length), 0),
      status: p.status || "active",
    })),
    contracts: Object.fromEntries(Object.entries(fbState.contracts || {}).map(([pid, list]) => [
      pid, list.map((c) => ({ ...c, house_count: (fbState.houses?.[c.id] || []).length }))
    ])),
    houses: Object.fromEntries(Object.entries(fbState.houses || {}).map(([cid, list]) => [
      cid, list.map((h) => ({ ...h, payments: (fbState.payments?.[h.id] || []).length }))
    ])),
    payments: fbState.payments || {},
    activity: [],
  };

  // Tweaks
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{ "layout": "sidebar" }/*EDITMODE-END*/;
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const layoutMode = t.layout || "sidebar";

  // ---- Auth gate ----
  if (!fbState.user) return (
    <ToastHost>
      <LoginScreen onLogin={async (email, pw) => {
        try { await window.FB.login(email, pw); return true; }
        catch (e) { return false; }
      }} />
    </ToastHost>
  );

  const counts = {
    projects: data.projects.length,
    contracts: Object.values(data.contracts).reduce((s, a) => s + a.length, 0),
    houses: Object.values(data.houses).reduce((s, a) => s + a.length, 0),
  };

  const nav = async (id) => {
    if (id === "logout") { await window.FB.logout(); return; }
    if (id === "contracts") return setRoute({ screen: "contracts", projectId: route.projectId || null });
    if (id === "houses") {
      if (route.contractId) return setRoute({ screen: "houses", projectId: route.projectId, contractId: route.contractId });
      return setRoute({ screen: "contracts", projectId: route.projectId || null });
    }
    setRoute({ screen: id });
  };

  const project = route.projectId ? data.projects.find((p) => p.id === route.projectId) : null;
  const contract = route.contractId && route.projectId ? (data.contracts[route.projectId] || []).find((c) => c.id === route.contractId) : null;

  const titles = { dashboard:"ภาพรวม", projects:"โครงการ", contracts:"สัญญา", houses:"บ้าน / ยูนิต", payments:"การเบิกจ่าย", reports:"รายงาน", settings:"ตั้งค่า" };
  const trail = [{ label: "หน้าหลัก", onClick: () => setRoute({ screen: "dashboard" }) }, { label: titles[route.screen] || "" }];
  if (route.screen === "contracts" && project) trail.push({ label: project.name });
  if (route.screen === "houses" && project && contract) {
    trail[1] = { label: "สัญญา", onClick: () => setRoute({ screen: "contracts", projectId: route.projectId }) };
    trail.push({ label: project.name, onClick: () => setRoute({ screen: "contracts", projectId: route.projectId }) });
    trail.push({ label: `${contract.contract_number}` });
  }

  // Handlers — wired to Firebase
  const handlers = {
    onAddProject: (p) => window.FB.addProject(p),
    onDeleteProject: (pid) => window.FB.deleteProject(pid),
    onUpdateProject: (pid, fields) => window.FB.updateProject(pid, fields),
    onAddContract: (pid, c) => window.FB.addContract(pid, c, c.file),
    onUpdateContract: (pid, cid, fields) => window.FB.updateContract(pid, cid, fields),
    onDeleteContract: (pid, cid, val, paid, attPath) => window.FB.deleteContract(pid, cid, val, paid, attPath),
    onAddHouse: (pid, cid, h) => window.FB.addHouse(pid, cid, h),
    onUpdateHouse: (pid, cid, hid, fields, oldPrice) => window.FB.updateHouse(pid, cid, hid, fields, oldPrice),
    onDeleteHouse: (pid, cid, hid, price, paid) => window.FB.deleteHouse(pid, cid, hid, price, paid),
    onAddPayment: async (pid, cid, hid, form) => {
      await window.FB.addPayment(pid, cid, hid, { date: form.date, inv: form.inv, amount: Number(form.amount), notes: form.notes }, form.file);
    },
    onDeletePayment: (pid, cid, hid, payId, amount, receiptPath) => window.FB.deletePayment(pid, cid, hid, payId, amount, receiptPath),
    onLoadPayments: (pid, cid, hid) => window.FB.loadPayments(pid, cid, hid),
  };

  let content = null;
  if (route.screen === "dashboard") {
    content = (
      <Dashboard
        data={data}
        onOpenProject={(pid) => { setSelectedProjectId(pid); setRoute({ screen: "contracts", projectId: pid }); }}
        onViewAllProjects={() => setRoute({ screen: "projects" })}
        onAddProject={handlers.onAddProject}
      />
    );
  } else if (route.screen === "projects") {
    content = (
      <ProjectsScreen
        data={data}
        selectedId={selectedProjectId}
        setSelectedId={setSelectedProjectId}
        onOpenContracts={(pid) => setRoute({ screen: "contracts", projectId: pid })}
        onAddProject={handlers.onAddProject}
        onDeleteProject={handlers.onDeleteProject}
        onUpdateProject={handlers.onUpdateProject}
      />
    );
  } else if (route.screen === "contracts") {
    content = (
      <ContractsScreen
        data={data}
        projectId={route.projectId}
        setProjectId={(pid) => setRoute({ screen: "contracts", projectId: pid })}
        onOpenHouses={(cid) => setRoute({ screen: "houses", projectId: route.projectId, contractId: cid })}
        onAddContract={handlers.onAddContract}
        onUpdateContract={(cid, fields) => handlers.onUpdateContract(route.projectId, cid, fields)}
        onDeleteContract={(cid, val, paid, attPath) => handlers.onDeleteContract(route.projectId, cid, val, paid, attPath)}
        onAddPayment={(cid, hid, form) => handlers.onAddPayment(route.projectId, cid, hid, form)}
      />
    );
  } else if (route.screen === "houses") {
    content = (
      <HousesScreen
        data={data}
        contractId={route.contractId}
        projectId={route.projectId}
        onBack={() => setRoute({ screen: "contracts", projectId: route.projectId })}
        onAddHouse={handlers.onAddHouse}
        onAddPayment={handlers.onAddPayment}
        onUpdateHouse={(hid, fields, oldPrice) => handlers.onUpdateHouse(route.projectId, route.contractId, hid, fields, oldPrice)}
        onDeleteHouse={(hid, price, paid) => handlers.onDeleteHouse(route.projectId, route.contractId, hid, price, paid)}
        onDeletePayment={(hid, payId, amount, receiptPath) => handlers.onDeletePayment(route.projectId, route.contractId, hid, payId, amount, receiptPath)}
        onLoadPayments={(hid) => handlers.onLoadPayments(route.projectId, route.contractId, hid)}
      />
    );
  } else if (route.screen === "reports") {
    content = <ReportsScreen data={data} />;
  } else if (route.screen === "settings") {
    content = <SettingsScreen />;
  } else if (route.screen === "payments") {
    content = <PaymentsScreen data={data} />;
  }

  return (
    <ToastHost>
      <div className={`shell ${layoutMode === "topnav" ? "topnav" : ""}`}>
        {layoutMode === "topnav" ? <TopNav active={route.screen} onNav={nav} counts={counts} /> : <Sidebar active={route.screen} onNav={nav} counts={counts} />}
        <div className="main">
          <Crumb trail={trail} />
          <div className="scroll">{content}</div>
        </div>
      </div>
      <TweaksPanel title="Tweaks">
        <TweakSection label="Layout">
          <TweakRadio label="Navigation" value={layoutMode}
            options={[{ value: "sidebar", label: "Sidebar" }, { value: "topnav", label: "Top nav" }]}
            onChange={(v) => setTweak("layout", v)} />
        </TweakSection>
      </TweaksPanel>
    </ToastHost>
  );
}

// Cross-project payments view
function PaymentsScreen({ data }) {
  const { fmt, fmtDate, Icon } = window;
  const all = [];
  Object.entries(data.payments || {}).forEach(([hid, list]) => {
    list.forEach((p) => {
      let house = null, contract = null, project = null;
      for (const cid of Object.keys(data.houses)) {
        const h = data.houses[cid].find((x) => x.id === hid);
        if (h) { house = h;
          for (const pid of Object.keys(data.contracts)) {
            const c = data.contracts[pid].find((x) => x.id === cid);
            if (c) { contract = c; project = data.projects.find((pr) => pr.id === pid); break; }
          } break;
        }
      }
      all.push({ ...p, house, contract, project });
    });
  });
  all.sort((a, b) => (b.date > a.date ? 1 : -1));
  const total = all.reduce((s, p) => s + p.amount, 0);
  return (
    <div className="page">
      <div className="page-head">
        <div><h1 className="page-title">การเบิกจ่ายทั้งหมด</h1><p className="page-sub">รายการเบิกจ่ายข้ามทุกโครงการ</p></div>
      </div>
      <div className="stat-grid">
        <div className="stat"><div className="label">รายการทั้งหมด</div><div className="value">{all.length}</div></div>
        <div className="stat accent-green"><div className="label">ยอดรวม</div><div className="value" style={{ color: "var(--success)" }}>฿{fmt(total)}</div></div>
        <div className="stat"><div className="label">เฉลี่ย/รายการ</div><div className="value">฿{fmt(Math.round(total / Math.max(1, all.length)))}</div></div>
      </div>
      <div className="card card-flush">
        <div className="card-head"><h3>รายการเบิกล่าสุด</h3></div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>วันที่</th><th>โครงการ / สัญญา</th><th>รหัสบ้าน</th><th>เลขใบกำกับ</th><th className="r">ยอด</th></tr></thead>
            <tbody>
              {all.map((p) => (
                <tr key={p.id}>
                  <td className="mono">{fmtDate(p.date)}</td>
                  <td><div className="strong" style={{ fontSize: 12.5 }}>{p.project?.name || "—"}</div><div className="dim mono" style={{ fontSize: 11 }}>{p.contract?.contract_number}</div></td>
                  <td className="mono strong">{p.house?.house_code}</td>
                  <td className="mono">{p.inv}</td>
                  <td className="r num strong" style={{ color: "var(--success)" }}>฿{fmt(p.amount)}</td>
                </tr>
              ))}
              {all.length === 0 && <tr><td colSpan={5} className="c dim" style={{ padding: 40 }}>ยังไม่มีการเบิกจ่าย</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

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