// sv-store.jsx — Form state engine + readiness scoring

const { createContext, useContext, useEffect, useState } = React;

const defaultIntakeData = {
  companyName: "", facilityName: "", facilityAddress: "",
  contactName: "", contactTitle: "", contactEmail: "", contactPhone: "",
  facilityType: "3PL warehouse", facilitySize: "25k-75k sq ft",
  employees: "25-50", operatingDays: "Mon-Fri", operatingHours: "6am-6pm",
  shiftsPerDay: "2 shifts",
  shiftSchedules: [
    { id: "1", name: "Shift 1", start: "06:00", end: "14:00", days: "Mon-Fri" },
    { id: "2", name: "Shift 2", start: "14:00", end: "22:00", days: "Mon-Fri" }
  ],
  bottleneck: "", incidents: "", hasCameras: "", plansToInstallCameras: "",
  zoneSOPs: {},
  zones: [{ id: "1", name: "Packing stations", cameras: "4", issues: "" }],
  workflows: ["Packing"],
  goals: ["End-of-shift reports", "Incident detection"],
  reportFrequency: "End of shift", successLookLike: "",
  problemsToIdentify: "", reviewers: "", vmsProvider: "",
  loginUrl: "", files: [], notes: "",
  acks: {
    limitedScope: false, readOnly: false, defaultRetention: false,
    docsConfig: false, modelConsent: false, authorized: false
  },
  internalSecurityReqs: ""
};

function calculateReadinessScore(data) {
  let score = 0;
  if (data.companyName && data.contactEmail) score += 1;
  if (data.facilityType) score += 1;
  if (data.zones && data.zones.length > 0 && data.zones[0].name) score += 1;
  const hasWorkflows = data.zones && data.zones.some(z => z.workflows && z.workflows.length > 0);
  if (hasWorkflows || (data.workflows && data.workflows.length > 0)) score += 1;
  if (data.goals && data.goals.length > 0) score += 1;
  if (data.successLookLike || data.problemsToIdentify || data.bottleneck) score += 1;
  if (data.hasCameras === "Yes") score += 2;
  else if (
    data.plansToInstallCameras === "Yes, we are planning to install our own" ||
    data.plansToInstallCameras === "Yes, we need cameras provided"
  ) score += 1;
  if (data.vmsProvider && data.vmsProvider !== "I'm not sure") score += 1;
  const hasSOPs = data.zoneSOPs && Object.values(data.zoneSOPs).some(f => f && f.length > 0);
  if (hasSOPs || (data.files && data.files.length > 0)) score += 1;
  return Math.min(10, score);
}

const FormContext = createContext(undefined);

function FormProvider({ children }) {
  const [data, setData] = useState(() => {
    try {
      const saved = localStorage.getItem("svNewIntake");
      if (saved) {
        const p = JSON.parse(saved);
        return {
          ...defaultIntakeData, ...p,
          zones: p.zones || defaultIntakeData.zones,
          workflows: p.workflows || defaultIntakeData.workflows,
          shiftSchedules: (p.shiftSchedules && p.shiftSchedules.length >= defaultIntakeData.shiftSchedules.length) ? p.shiftSchedules : defaultIntakeData.shiftSchedules,
          goals: p.goals || defaultIntakeData.goals,
          files: p.files || defaultIntakeData.files,
          acks: { ...defaultIntakeData.acks, ...(p.acks || {}) }
        };
      }
    } catch (e) {}
    return defaultIntakeData;
  });

  useEffect(() => {
    localStorage.setItem("svNewIntake", JSON.stringify(data));
  }, [data]);

  const updateData = (payload) => setData(prev => ({ ...prev, ...payload }));
  const updateAcks = (payload) => setData(prev => ({ ...prev, acks: { ...prev.acks, ...payload } }));
  const resetData = () => { setData(defaultIntakeData); localStorage.removeItem("svNewIntake"); };

  const SUBMIT_API = 'https://dd6vq097rc.execute-api.us-east-1.amazonaws.com/default/submit';

  const submitForm = () => {
    const submissions = JSON.parse(localStorage.getItem("svSubmissions") || "[]");
    const score = calculateReadinessScore(data);
    const status = score >= 8 ? "Ready for setup" : score >= 5 ? "Waiting on SOPs" : "New submission";
    const newSub = { ...data, id: crypto.randomUUID(), submittedAt: new Date().toISOString(), score, status };
    submissions.push(newSub);
    localStorage.setItem("svSubmissions", JSON.stringify(submissions));

    // Everything below this point is best-effort telemetry (persisting a copy to S3 +
    // notifying the team). It must never be able to block or crash the submission —
    // the local save above is what makes the form authoritative, so we wrap the rest
    // in a try/catch and defensively guard against malformed data shapes.
    try {
      // Build API payload - include file content (dataUrl) so the admin portal can
      // download/view uploads. Guard against huge files blowing past API payload limits
      // by only including the dataUrl when the file is reasonably small.
      const MAX_INLINE_FILE_BYTES = 4 * 1024 * 1024; // 4MB
      const packFile = (f) => ({
        name: f && f.name,
        size: f && f.size,
        type: f && f.type,
        ...(f && f.dataUrl && f.size && f.size <= MAX_INLINE_FILE_BYTES ? { dataUrl: f.dataUrl } : {}),
      });
      const asFileArray = (v) => (Array.isArray(v) ? v.filter(Boolean).map(packFile) : []);
      const apiPayload = {
        ...newSub,
        zoneSOPs: Object.fromEntries(
          Object.entries(newSub.zoneSOPs || {}).map(([k, files]) => [
            k, asFileArray(files)
          ])
        ),
        files: asFileArray(newSub.files),
      };

      // Persist to S3 + trigger email notification (fire-and-forget)
      fetch(SUBMIT_API, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(apiPayload),
      }).catch(err => console.warn('Submit API error:', err));
    } catch (err) {
      // Never let a malformed field (e.g. a corrupted zoneSOPs/files value) stop the
      // user from seeing the confirmation screen. Log it so it's visible in the
      // console for debugging, but don't rethrow.
      console.warn('submitForm: non-fatal error building/sending API payload:', err);
    }

    resetData();
    return newSub;
  };

  return React.createElement(FormContext.Provider,
    { value: { data, updateData, updateAcks, resetData, submitForm } },
    children
  );
}

function useFormContext() {
  const ctx = useContext(FormContext);
  if (!ctx) throw new Error("useFormContext must be used within FormProvider");
  return ctx;
}

Object.assign(window, { FormProvider, useFormContext, calculateReadinessScore, defaultIntakeData });
