// NCS Presale — live data from D1 via Pages Functions
const STAGE_COLORS = {
  'Requirement': '#6366f1', 'Proposal': '#0ea5e9', 'POC / Demo': '#8b5cf6',
  'Negotiation': '#f59e0b', 'Win / Handover': '#10b981', 'Lost': '#f43f5e',
};
const STAGES = ['Requirement', 'Proposal', 'POC / Demo', 'Negotiation', 'Win / Handover', 'Lost'];

// Initialise empty — populated after API load
window.PROJECTS = [];
window.SALES    = [];
window.PRESALES = [];
window.GROUPS   = [];
window.QUARTERS = [];

function compact(v) {
  return new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }).format(v || 0);
}
function baht(v) { return '฿' + compact(v); }

function parseWin(str) {
  return parseInt((str || '0').replace('%', ''), 10) || 0;
}

function computeQuarters(projects) {
  const thisYY = String(new Date().getFullYear()).slice(2);
  const active = projects.filter(p => p.stage !== 'Lost');
  const qmap = {};
  active.forEach(p => {
    if (!p.estimate_close || p.estimate_close === 'Unknown') return;
    const m = p.estimate_close.match(/^(Q[1-4])(?:\s+(\d{4}))?$/);
    if (!m) return;
    const yy = m[2] ? m[2].slice(2) : thisYY;
    const key = `${m[1]} ${yy}`;
    if (!qmap[key]) qmap[key] = { quarter: key, pipeline: 0, weighted: 0 };
    qmap[key].pipeline = Math.round((qmap[key].pipeline + p.value / 1e6) * 10) / 10;
    qmap[key].weighted = Math.round((qmap[key].weighted + (p.value * p.win / 100) / 1e6) * 10) / 10;
  });
  return Object.values(qmap)
    .sort((a, b) => {
      const [aq, ay] = a.quarter.split(' ');
      const [bq, by] = b.quarter.split(' ');
      return ay !== by ? ay.localeCompare(by) : aq.localeCompare(bq);
    })
    .slice(-8);
}

function useData() {
  const [state, setState] = React.useState({ loading: true, error: null });

  React.useEffect(() => {
    Promise.all([
      fetch('/api/projects').then(r => { if (!r.ok) throw new Error('Failed to load projects'); return r.json(); }),
      fetch('/api/lookup').then(r =>   { if (!r.ok) throw new Error('Failed to load lookup');   return r.json(); }),
    ]).then(([projData, lookupData]) => {
      const projects = (projData.projects || []).map(p => ({
        id:      p.ncs_code,
        ncs:     p.ncs_code,
        customer: p.customer,
        project:  p.project_name,
        sale:     p.sale_owner,
        group:    p.sale_group,
        presale:  p.presale_owner,
        team:     p.presale_team,
        vendor:   p.vendors   ? p.vendors.split('|')[0]   : '—',
        solution: p.solutions ? p.solutions.split('|')[0] : '—',
        stage:    p.update_stage || 'Requirement',
        win:      parseWin(p.win_probability),
        value:    p.total_value || 0,
        status:   p.workload_status === 'Active' ? 'Active' : 'Inactive',
        estimate_close: p.estimate_close,
        last_action:    p.last_action,
        updated_at:     p.updated_at,
      }));

      window.PROJECTS = projects;
      window.SALES    = [...new Set(projects.map(p => p.sale).filter(Boolean))].sort();
      window.PRESALES = [...new Set(projects.map(p => p.presale).filter(Boolean))].sort();
      window.GROUPS   = [...new Set(projects.map(p => p.group).filter(Boolean))].sort();
      window.QUARTERS = computeQuarters(projects);

      // Expose lookup data for dropdowns
      window.NCS_LOOKUP = lookupData;

      setState({ loading: false, error: null });
    }).catch(err => {
      setState({ loading: false, error: err.message });
    });
  }, []);

  return state;
}

// ── Responsive + theme helpers ───────────────────────────────
function useMediaQuery(query) {
  const [match, setMatch] = React.useState(() => typeof window !== 'undefined' && window.matchMedia(query).matches);
  React.useEffect(() => {
    const mq = window.matchMedia(query);
    const on = e => setMatch(e.matches);
    mq.addEventListener('change', on);
    setMatch(mq.matches);
    return () => mq.removeEventListener('change', on);
  }, [query]);
  return match;
}
const useIsMobile = () => useMediaQuery('(max-width: 720px)');

function useTheme() {
  const read = () => {
    try { return localStorage.getItem('ncs-theme') || 'dark'; } catch (e) { return 'dark'; }
  };
  const [theme, setTheme] = React.useState(read);
  React.useEffect(() => {
    document.documentElement.dataset.theme = theme;
    try { localStorage.setItem('ncs-theme', theme); } catch (e) {}
  }, [theme]);
  return [theme, () => setTheme(t => (t === 'dark' ? 'light' : 'dark'))];
}

Object.assign(window, { STAGE_COLORS, STAGES, compact, baht, useData, useMediaQuery, useIsMobile, useTheme });
