import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import LoginScreen from "./LoginScreen.jsx";
import { configLooksValid, getSession, onAuthChange, installStorage, signOut, isStaging, supabase } from "./lib/supabaseStorage";
import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";

// Turn a rendered document (the invoice / PO sheet) into a PDF, returned as base64. Letter size, multi-page.
async function renderPdf(node) {
  const canvas = await html2canvas(node, { scale: 2, useCORS: true, backgroundColor: "#ffffff", logging: false });
  const pdf = new jsPDF({ unit: "pt", format: "letter", orientation: "portrait" });
  const pw = pdf.internal.pageSize.getWidth(), ph = pdf.internal.pageSize.getHeight();
  const pxPerPt = canvas.width / pw, pagePx = Math.floor(ph * pxPerPt);
  let offset = 0, page = 0;
  while (offset < canvas.height) {
    const slice = document.createElement("canvas");
    slice.width = canvas.width; slice.height = Math.min(pagePx, canvas.height - offset);
    slice.getContext("2d").drawImage(canvas, 0, offset, canvas.width, slice.height, 0, 0, canvas.width, slice.height);
    if (page > 0) pdf.addPage();
    pdf.addImage(slice.toDataURL("image/jpeg", 0.92), "JPEG", 0, 0, pw, slice.height / pxPerPt);
    offset += slice.height; page++;
  }
  return pdf.output("datauristring").split(",")[1];
}

// Signed-in user's role (from user_roles; 'readonly' if not listed) and the admin user-management bridge.
async function loadRole(session) {
  const email = (session && session.user && session.user.email) || "";
  let role = "readonly";
  try {
    const { data } = await supabase().from("user_roles").select("role, active, display_name").ilike("email", email).maybeSingle();
    if (data && data.active !== false) role = data.role || "readonly";
  } catch (e) { /* default readonly */ }
  window.__acnodesUser = { email, role };
  return role;
}
function installUsersBridge() {
  window.__acnodesUsers = {
    call: async (payload) => {
      const { data, error } = await supabase().functions.invoke("manage-users", { body: payload });
      if (error) { let msg = error.message || String(error); try { const j = await error.context.json(); if (j && j.error) msg = j.error; } catch (e) { /* keep */ } return { ok: false, error: msg }; }
      return data || { ok: false, error: "No response" };
    },
  };
}

function installAuditBridge() {
  const site = () => (isStaging() ? "staging" : "live");
  window.__acnodesAudit = {
    write: async (events) => { const rows = events.map((e) => ({ who: e.who, site: site(), module: e.module, record: String(e.record), action: e.action, summary: e.summary || null, changes: e.changes || [] })); const { error } = await supabase().from("erp_audit").insert(rows); if (error) console.warn("audit write failed", error.message); },
    read: async (module, record, limit) => { const { data } = await supabase().from("erp_audit").select("at, who, action, summary, changes").eq("site", site()).eq("module", module).eq("record", String(record)).order("at", { ascending: false }).limit(limit || 100); return data || []; },
    recent: async (limit) => { const { data } = await supabase().from("erp_audit").select("at, who, module, record, action, summary").eq("site", site()).order("at", { ascending: false }).limit(limit || 100); return data || []; },
  };
}

function installMailer() {
  window.__acnodesRenderPdf = renderPdf;
  window.__acnodesMailer = {
    send: async (payload) => {
      const { data, error } = await supabase().functions.invoke("send-email", { body: payload });
      if (error) {
        let msg = error.message || String(error);
        try { const j = await error.context.json(); if (j && j.error) msg = j.error; } catch (e) { /* keep msg */ }
        return { ok: false, error: msg };
      }
      return data || { ok: false, error: "No response from mail service" };
    },
  };
}

function ConfigProblem() {
  return (
    <div style={{ fontFamily: "system-ui, sans-serif", padding: 40, maxWidth: 640, margin: "60px auto", background: "#FFF6EA", border: "1px solid #EFD9AE", borderRadius: 12, color: "#7A5A17" }}>
      <h2 style={{ marginTop: 0 }}>Almost there — the app isn't connected to your database yet.</h2>
      <p>Open the file <code>config.js</code> (it sits next to <code>index.html</code>) in a text editor and paste in your Supabase <strong>Project URL</strong> and <strong>anon public key</strong> from Supabase → Project Settings → API. Then reload this page.</p>
      <p style={{ fontSize: 13 }}>See <strong>SETUP-GUIDE.md</strong> for the step-by-step.</p>
    </div>
  );
}

function Root() {
  const [session, setSession] = useState(undefined); // undefined = still checking
  const [role, setRole] = useState(null);
  useEffect(() => {
    if (!configLooksValid()) { setSession(null); return; }
    getSession().then(setSession);
    const { data } = onAuthChange((s) => setSession(s));
    return () => data && data.subscription && data.subscription.unsubscribe();
  }, []);

  if (!configLooksValid()) return <ConfigProblem />;
  if (session === undefined) return <div style={{ fontFamily: "system-ui, sans-serif", padding: 40, color: "#64748B" }}>Loading…</div>;
  if (!session) return <LoginScreen onSignedIn={setSession} staging={isStaging()} />;
  if (role === null) { loadRole(session).then(setRole); return <div style={{ fontFamily: "system-ui, sans-serif", padding: 40, color: "#64748B" }}>Loading…</div>; }

  installStorage();
  installMailer();
  installUsersBridge();
  installAuditBridge();
  const staging = isStaging();
  return (
    <>
      {staging && (
        <div style={{ position: "fixed", top: 0, left: 0, right: 0, zIndex: 10000, background: "#D97706", color: "#fff", fontSize: 12, fontWeight: 700, textAlign: "center", padding: "5px 0", letterSpacing: 0.3 }}>
          STAGING — testing copy, separate from the live site your team uses
        </div>
      )}
      <div style={{ paddingTop: staging ? 28 : 0 }}>
        <App />
      </div>
      <button
        onClick={() => signOut()}
        title={session.user && session.user.email}
        style={{ position: "fixed", right: 14, bottom: 14, zIndex: 9999, padding: "6px 12px", border: "1px solid #CBD5E1", borderRadius: 8, background: "#fff", color: "#475569", fontSize: 12, cursor: "pointer", boxShadow: "0 2px 8px rgba(0,0,0,0.08)" }}
      >
        Sign out ({session.user && session.user.email})
      </button>
    </>
  );
}

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