// === Shared state hook + defaults ===
const STORAGE_KEY = "pm_atelier_v1";

const DEFAULT_STATE = {
  // Section 1 - Organization
  org: {
    projectTitle: "",
    authorName: "",
    date: new Date().toLocaleDateString("ro-RO"),
    location: "",
    name: "",
    locality: "",
    county: "",
    activity: "",
    employees: "",
    turnover: "",
    profit: "",
    product: ""
  },
  // Section 2 - Scope
  scope: {
    text: "",
    type: "needs", // "funds" | "needs"
    focus: "proposal", // "proposal" | "decision"
    breadth: "specific" // "broad" | "specific"
  },
  // Section 3 - SWOT / needs
  needs: {
    innovation: "",
    beneficiaries: "",
    resources: "",
    swot: {
      s: [],
      w: [],
      o: [],
      t: []
    }
  },
  // Section 4 - Activities + SMART
  activities: [
    { id: 1, name: "", duration: "", result: "", budget: "", start: 1, end: 3, smart: { s: false, m: false, a: false, r: false, t: false } }
  ],
  generalObjective: "",
  // Section 5 - Gantt is derived from activities
  // Section 6 - Budget
  budget: {
    total: 100000,
    items: [
      { id: "personal", title: "Cheltuieli de personal", desc: "Echipa managerială, logistica (materiale, consumabile, întreținere echipamente)", pct: 8, min: 5, max: 10 },
      { id: "dotari", title: "Dotări", desc: "Active corporale și necorporale: utilaje, echipamente IT, mobilier, soft-uri, certificări", pct: 72, min: 70, max: 75 },
      { id: "mobilitati", title: "Mobilități", desc: "Deplasare, cazare, diurnă, taxe participare", pct: 3, min: 3, max: 4 },
      { id: "publicitate", title: "Informare și publicitate", desc: "Anunțuri presă, articole, banner, flyere, broșuri, autocolante", pct: 2, min: 1, max: 2 },
      { id: "consultanta", title: "Consultanță", desc: "Scriere/depunere proiect, implementare, monitorizare ex-post", pct: 6, min: 5, max: 7 },
      { id: "indirecte", title: "Cheltuieli indirecte (regie)", desc: "Utilități, chirie, alte taxe", pct: 1, min: 1, max: 2 }
    ]
  },
  // Section 7 - Management
  management: {
    leader: "",
    members: [
      { role: "Manager de proiect", name: "" },
      { role: "Responsabil tehnic", name: "" },
      { role: "Responsabil financiar", name: "" }
    ],
    communication: "",
    monitoring: ""
  },
  // Section 8 - Risk
  risks: [
    { id: 1, name: "", strategy: "", effect: "", prob: 3, impact: 3 }
  ],
  // Module 1 progress
  m1: {
    completedLessons: [],
    definitionsViewed: [],
    pertActivities: [
      { id: 1, code: "A", name: "Analiză cerințe", duration: 5, deps: [] },
      { id: 2, code: "B", name: "Design tehnic", duration: 8, deps: [1] },
      { id: 3, code: "C", name: "Prototip UI", duration: 6, deps: [1] },
      { id: 4, code: "D", name: "Implementare backend", duration: 12, deps: [2] },
      { id: 5, code: "E", name: "Implementare frontend", duration: 10, deps: [3] },
      { id: 6, code: "F", name: "Testare integrare", duration: 4, deps: [4, 5] },
      { id: 7, code: "G", name: "Deploy & training", duration: 3, deps: [6] }
    ],
    eisenhowerTasks: [
      { id: 1, text: "Răspunde la email-uri de la client", quadrant: null },
      { id: 2, text: "Planificare strategică Q3", quadrant: null },
      { id: 3, text: "Workshop intern lunar", quadrant: null },
      { id: 4, text: "Stins focuri din ticket-uri urgente", quadrant: null },
      { id: 5, text: "Apel social media non-urgent", quadrant: null },
      { id: 6, text: "Update săptămânal echipă", quadrant: null },
      { id: 7, text: "Briefing crizei de buget marți", quadrant: null },
      { id: 8, text: "Învățați un nou tool de PM", quadrant: null }
    ],
    glossarySeen: [],
    quizScore: null,
    quizAttempts: 0
  },
  // Module 3 simulator state
  m3: {
    scenarioId: null,
    state: null,
    finished: false,
    finalScore: null,
    aiReport: null
  },
  // Module 4 gamification state
  m4: {
    examScore: null,
    examAttempts: 0,
    examTimestamp: null
  },
  // Module 3 team simulation state
  m3team: {
    players: [],
    scenarioId: null,
    state: null,
    finished: false,
    teamScore: null,
    coordinationScore: null,
    roleScores: {}
  },
  // Module 2 — multi-project meta. The top-level fields above (org, scope,
  // needs, activities, budget, management, risks, generalObjective) hold the
  // ACTIVE project's data. m2.activeProjectId tracks which one.
  m2: {
    activeProjectId: null,         // null = unsaved scratch project
    activeProjectTitle: "",        // for display in M2 header
    projectsList: []               // cached metadata (refreshed on load)
  }
};

// Synchronous initial load from localStorage — for first render before
// async Storage.loadState() resolves. Keeps the app responsive.
function loadStateSync() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return DEFAULT_STATE;
    const parsed = JSON.parse(raw);
    return { ...DEFAULT_STATE, ...parsed };
  } catch (e) {
    return DEFAULT_STATE;
  }
}

function useAppState() {
  // First render uses localStorage immediately (no flicker).
  const [state, setState] = React.useState(loadStateSync);

  // After mount, if Supabase is configured AND user is logged in,
  // load the cloud state and replace local. window.Storage handles
  // the merge logic (newest wins).
  React.useEffect(() => {
    if (!window.Storage) return;
    let cancelled = false;
    window.Storage.loadState(DEFAULT_STATE).then(remote => {
      if (cancelled) return;
      // Only replace if remote actually came from cloud (has different _meta).
      // For anonymous users, loadState returns the same localStorage content
      // we already have — no-op.
      const remoteMeta = remote?._meta?.updatedAt || 0;
      const localMeta = state?._meta?.updatedAt || 0;
      if (remoteMeta > localMeta) {
        setState(remote);
      }
    }).catch(() => {});
    return () => { cancelled = true; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Save on every state change. Storage.saveState writes to BOTH
  // localStorage (always) and Supabase (when logged in).
  React.useEffect(() => {
    if (window.Storage) {
      window.Storage.saveState(state).catch(() => {});
    } else {
      // Fallback if storage.jsx didn't load (shouldn't happen)
      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch (e) {}
    }
  }, [state]);

  // Debounced auto-save of M2 fields to the active project's row.
  // Only fires when an active project is set and the user is authenticated.
  React.useEffect(() => {
    const activeId = state.m2?.activeProjectId;
    if (!activeId || !window.Storage?.updateProject) return;
    const timer = setTimeout(() => {
      window.Storage.updateProject(activeId, {
        data: extractM2ProjectData(state)
      }).catch(() => {});
    }, 1200);  // debounce 1.2s of inactivity
    return () => clearTimeout(timer);
  }, [
    state.m2?.activeProjectId,
    state.org, state.scope, state.needs,
    state.activities, state.generalObjective,
    state.budget, state.management, state.risks
  ]);

  const update = React.useCallback((updater) => {
    setState(prev => {
      const next = typeof updater === "function" ? updater(prev) : { ...prev, ...updater };
      return next;
    });
  }, []);

  const reset = React.useCallback(() => {
    if (window.Storage) {
      window.Storage.resetState().catch(() => {});
    } else {
      localStorage.removeItem(STORAGE_KEY);
    }
    setState(DEFAULT_STATE);
  }, []);

  return [state, update, reset];
}

// SMART validation logic (heuristic)
function evaluateSMART(activity) {
  const t = (activity.name || "").trim();
  const wordCount = t.split(/\s+/).filter(Boolean).length;
  const hasNumber = /\d/.test(t + " " + (activity.result || ""));
  const hasVerb = /\b(crea|realiza|dezvolt|implementa|achizit|elabor|testa|valida|instala|forma|certific|publicat|finaliz|consolid|optimiz|configur|integra|monitoriza|evalua|produce|livra|prezenta|organiza|coordona)\w*/i.test(t);
  const durationOk = !!activity.duration && activity.duration.trim().length > 0;
  const budgetOk = !!activity.budget && parseInt(activity.budget) > 0;
  const resultOk = !!activity.result && activity.result.trim().length > 4;
  return {
    s: wordCount >= 4 && hasVerb,        // Specific
    m: hasNumber || resultOk,             // Measurable
    a: hasVerb && resultOk,               // Achievable - sensible result
    r: budgetOk && resultOk,              // Realistic - has budget + result
    t: durationOk                         // Time - duration set
  };
}

// Romanian month labels
const MONTHS = ["L1","L2","L3","L4","L5","L6","L7","L8","L9","L10","L11","L12"];

// Modules — the broader platform structure
const MODULES = [
  {
    id: "m1",
    code: "M1",
    name: "Teorie interactivă",
    blurb: "Concepte PM vizualizate: PERT, Eisenhower, organigrame, glosar searchable.",
    status: "active",
    route: "m1-overview"
  },
  {
    id: "m2",
    code: "M2",
    name: "Instrumente de proiect",
    blurb: "Constructor live de propunere — SWOT, SMART, Gantt, buget, risc, export.",
    status: "active",
    route: "m2-overview"
  },
  {
    id: "m3",
    code: "M3",
    name: "Simulator de proiect",
    blurb: "Conduci un proiect virtual. Decizii cu consecințe. Feedback AI.",
    status: "active",
    route: "m3-overview"
  },
  {
    id: "m4",
    code: "M4",
    name: "Gamificare & evaluare",
    blurb: "Quiz pe subiectele grilă ANC, badge-uri, certificat de parcurgere.",
    status: "active",
    route: "m4-overview"
  }
];

// Section labels — all routes
const SECTIONS = [
  { id: "intro", num: "00", label: "Acasă", group: "PLATFORMĂ", module: "home" },
  { id: "m1-overview", num: "M1", label: "Modul 1 · Prezentare", group: "PLATFORMĂ", module: "m1" },
  { id: "m1-definitions", num: "1.1", label: "Definiții animate", group: "PLATFORMĂ", module: "m1" },
  { id: "m1-pert", num: "1.2", label: "Diagrama PERT", group: "PLATFORMĂ", module: "m1" },
  { id: "m1-eisenhower", num: "1.3", label: "Matricea Eisenhower", group: "PLATFORMĂ", module: "m1" },
  { id: "m1-orgs", num: "1.4", label: "Organigrame comparație", group: "PLATFORMĂ", module: "m1" },
  { id: "m1-glossary", num: "1.5", label: "Glosar de termeni", group: "PLATFORMĂ", module: "m1" },
  { id: "m1-quiz", num: "1.Q", label: "Quiz Modul 1", group: "PLATFORMĂ", module: "m1" },
  { id: "m2-overview", num: "M2", label: "Modul 2 · Prezentare", group: "PLATFORMĂ", module: "m2" },
  { id: "org", num: "01", label: "Date organizație", group: "CADRU", module: "m2" },
  { id: "scope", num: "02", label: "Scop / Ideea de proiect", group: "CADRU", module: "m2" },
  { id: "needs", num: "03", label: "Analiză nevoi & SWOT", group: "CADRU", module: "m2" },
  { id: "activities", num: "04", label: "Plan activități (SMART)", group: "EXECUȚIE", module: "m2" },
  { id: "gantt", num: "05", label: "Diagrama GANTT", group: "EXECUȚIE", module: "m2" },
  { id: "budget", num: "06", label: "Plan financiar", group: "EXECUȚIE", module: "m2" },
  { id: "mgmt", num: "07", label: "Management proiect", group: "GUVERNANȚĂ", module: "m2" },
  { id: "risk", num: "08", label: "Analiză de risc", group: "GUVERNANȚĂ", module: "m2" },
  { id: "export", num: "09", label: "Document final", group: "FINAL", module: "m2" },
  { id: "m3-overview", num: "M3", label: "Modul 3 · Prezentare", group: "PLATFORMĂ", module: "m3" },
  { id: "m3-sim", num: "▶", label: "Simulator activ", group: "PLATFORMĂ", module: "m3" },
  { id: "m3-report", num: "✓", label: "Raport simulare", group: "PLATFORMĂ", module: "m3" },
  { id: "m3-team-setup", num: "⬢", label: "Simulare echipă", group: "PLATFORMĂ", module: "m3" },
  { id: "m3-team-sim", num: "▶", label: "Simulator echipă", group: "PLATFORMĂ", module: "m3" },
  { id: "m3-team-report", num: "✓", label: "Raport echipă", group: "PLATFORMĂ", module: "m3" },
  { id: "m4-overview", num: "M4", label: "Profil & Badge-uri", group: "PLATFORMĂ", module: "m4" },
  { id: "m4-exam", num: "4.X", label: "Mock Exam ANC", group: "PLATFORMĂ", module: "m4" },
  { id: "m4-certificate", num: "Ⓜ", label: "Certificat", group: "PLATFORMĂ", module: "m4" },
  { id: "history", num: "📊", label: "Istoricul meu", group: "CONT", module: "account" },
  { id: "privacy", num: "🔒", label: "Datele mele", group: "CONT", module: "account" }
];

// Sections that count toward completion progress (Module 2 tools only)
const M2_TOOL_IDS = ["org", "scope", "needs", "activities", "gantt", "budget", "mgmt", "risk"];
const M1_LESSON_IDS = ["m1-definitions", "m1-pert", "m1-eisenhower", "m1-orgs", "m1-glossary", "m1-quiz"];

// M1 progress logic
function m1LessonComplete(id, s) {
  if (!s.m1) return false;
  if (id === "m1-quiz") return s.m1.quizScore !== null && s.m1.quizScore >= 60;
  return (s.m1.completedLessons || []).includes(id);
}

// Helper used by lesson Continue buttons
function markM1LessonDone(id, update) {
  update(s => {
    const list = s.m1.completedLessons || [];
    if (list.includes(id)) return s;
    return { ...s, m1: { ...s.m1, completedLessons: [...list, id] }};
  });
}

// Section completion logic
function sectionComplete(id, s) {
  switch (id) {
    case "org": return !!s.org.projectTitle && !!s.org.name && !!s.org.activity;
    case "scope": {
      const wc = (s.scope.text || "").trim().split(/\s+/).filter(Boolean).length;
      return wc >= 8 && wc <= 50;
    }
    case "needs": return !!s.needs.innovation && (s.needs.swot.s.length + s.needs.swot.w.length + s.needs.swot.o.length + s.needs.swot.t.length) >= 4;
    case "activities": return s.activities.filter(a => a.name && a.name.trim()).length >= 2;
    case "gantt": return s.activities.some(a => a.name && a.name.trim());
    case "budget": {
      const sum = s.budget.items.reduce((a,b)=>a+(+b.pct||0),0);
      return sum === 100;
    }
    case "mgmt": return !!s.management.leader && s.management.members.every(m => m.name);
    case "risk": return s.risks.filter(r => r.name && r.strategy).length >= 1;
    default: return false;
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// M2 project helpers — pack/unpack the active project's data
// ─────────────────────────────────────────────────────────────────────────────

// Which top-level state keys belong to an M2 project
const M2_PROJECT_KEYS = ["org", "scope", "needs", "activities", "generalObjective", "budget", "management", "risks"];

/** Extract just the M2 project fields from the full app state. */
function extractM2ProjectData(state) {
  const out = {};
  M2_PROJECT_KEYS.forEach(k => { out[k] = state[k]; });
  return out;
}

/** Apply M2 project data back to the app state. Missing keys fall back to defaults. */
function applyM2ProjectData(state, projectData) {
  const next = { ...state };
  M2_PROJECT_KEYS.forEach(k => {
    next[k] = projectData?.[k] !== undefined ? projectData[k] : DEFAULT_STATE[k];
  });
  return next;
}

Object.assign(window, {
  useAppState, DEFAULT_STATE, evaluateSMART, MONTHS, SECTIONS, MODULES,
  M2_TOOL_IDS, M1_LESSON_IDS, M2_PROJECT_KEYS,
  m1LessonComplete, markM1LessonDone, sectionComplete,
  extractM2ProjectData, applyM2ProjectData
});
