/* integrations/FileUpload.jsx — single-file document upload row.
   Uploads to Supabase Storage ("tenant-docs") + inserts a `documents`
   row, with a DEMO simulation fallback when no Supabase client.
   Globals: React, Portal, Icon, window.portalSupabase, window.portalAnalytics.
   Exposes: FileUpload (global). */
/* eslint-disable */
const { useState: useFU, useRef: useRefFU } = React;

const FU_MAX_BYTES = 25 * 1024 * 1024; // 25MB
const FU_OK_MIME = ["application/pdf", "image/jpeg", "image/png", "image/heic", "image/heif"];

function fuSafeName(name) {
  return String(name || "file")
    .replace(/[^a-zA-Z0-9._-]+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(-120) || "file";
}
function fuUuid() {
  try { if (window.crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (e) {}
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
function fuMimeOk(file) {
  const t = (file.type || "").toLowerCase();
  if (t && FU_OK_MIME.indexOf(t) !== -1) return true;
  // Some browsers omit type for .heic — fall back to extension sniff.
  const n = (file.name || "").toLowerCase();
  return /\.(pdf|jpe?g|png|heic|heif)$/.test(n);
}

function FileUpload({ applicationId, documentType, label, why, accept, capture, onUploaded }) {
  const [busy, setBusy] = useFU(false);
  const [error, setError] = useFU(null);
  const [done, setDone] = useFU(null); // { filename }
  const inputRef = useRefFU(null);

  const acceptAttr = accept || "application/pdf,image/*";

  function pick() {
    setError(null);
    if (inputRef.current) { inputRef.current.value = ""; inputRef.current.click(); }
  }

  async function onFile(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setError(null);

    if (file.size > FU_MAX_BYTES) {
      setError("That file is over 25MB. Please upload a smaller PDF or photo.");
      return;
    }
    if (!fuMimeOk(file)) {
      setError("Please upload a PDF or a photo (JPG, PNG, or HEIC).");
      return;
    }

    setBusy(true);
    try {
      const doc = await uploadOne(file);
      setDone({ filename: doc.filename });
      window.portalAnalytics && window.portalAnalytics.log("document_uploaded", {
        step: "stage2", metadata: { document_type: documentType, filename: doc.filename }
      });
      onUploaded && onUploaded(doc);
    } catch (err) {
      console.error("[portal] upload failed", err);
      setError((err && err.message) || "Upload didn't go through. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  async function uploadOne(file) {
    const sb = window.portalSupabase;
    const filename = file.name || (documentType + ".pdf");
    const mime = (file.type || "application/octet-stream").toLowerCase();

    if (!sb) {
      await new Promise((r) => setTimeout(r, 700));
      console.warn("[portal] DEMO — upload simulated", { documentType, filename });
      return { filename, file_size_bytes: file.size, mime_type: mime, source: "upload" };
    }

    const BUCKET = (window.PORTAL_BUCKETS && window.PORTAL_BUCKETS.docs) || "tenant-portal-docs";
    const storage_path = applicationId + "/" + documentType + "/" + fuUuid() + "-" + fuSafeName(filename);
    const { error: uerr } = await sb.storage.from(BUCKET).upload(storage_path, file, {
      cacheControl: "3600", upsert: false, contentType: mime,
    });
    if (uerr) throw uerr;

    const row = {
      application_id: applicationId, document_type: documentType, source: "upload",
      storage_path: storage_path, filename: filename, file_size_bytes: file.size, mime_type: mime,
    };
    const { data, error: ierr } = await sb.from("documents").insert(row).select().single();
    if (ierr) throw ierr;
    return data || row;
  }

  return (
    <div className={Portal.cx("upload-row", done && "done")}>
      <div className="ur-meta">
        <div className="ur-name">
          {done && <Icon name="check" size={15} />} {label}
        </div>
        {done
          ? <div className="ur-why">{done.filename}</div>
          : (why ? <div className="ur-why">{why}</div> : null)}
        {error && <div className="field-err"><Icon name="alert" size={13} /> {error}</div>}
      </div>

      <div className="ur-action">
        <button type="button" className="btn ghost sm" onClick={pick} disabled={busy}>
          {busy
            ? <span className="spinner" aria-label="Uploading" />
            : (done ? "Replace" : <span><Icon name="upload" size={14} /> Upload</span>)}
        </button>
      </div>

      <input
        ref={inputRef}
        type="file"
        accept={acceptAttr}
        capture={capture || undefined}
        style={{ display: "none" }}
        onChange={onFile}
      />
    </div>
  );
}
