// YJ Electric — Booking & Quote Flow v2: data, helpers, shared UI
// Persona → property → work type → multi-select services → duration-aware scheduling.
// Depends on schedule-shared.jsx (SG, ServiceIcon, SLOTS, fmtDay, checkZip, workOrderNumber).

// ── WHO'S BOOKING ──────────────────────────────────────────
const V2_CUSTOMERS = [
  { key: 'homeowner', label: 'Homeowner',           sub: 'Work on my own home' },
  { key: 'agent',     label: 'Real Estate Agent',   sub: 'A listing or transaction' },
  { key: 'builder',   label: 'Builder / GC',        sub: 'Remodels & new builds' },
  { key: 'landlord',  label: 'Residential PM',     sub: 'Rental or managed property' },
  { key: 'business',  label: 'Commercial PM',       sub: 'My commercial space' },
];

// ── PROPERTY TYPES (gated by customer type) ────────────────
const V2_PROPS = [
  { key: 'residential', label: 'Single-Family', sub: 'House' },
  { key: 'multi',       label: 'Multi-Unit',    sub: 'Duplex, condo, townhome' },
  { key: 'commercial',  label: 'Commercial',    sub: 'Office, retail, warehouse' },
];
const V2_PROPS_BY_CUSTOMER = {
  homeowner: ['residential', 'multi'],
  landlord:  ['residential', 'multi'],
  agent:     ['residential', 'multi', 'commercial'],
  builder:   ['residential', 'multi', 'commercial'],
  business:  ['commercial'],
};

// ── WORK TYPES (per customer type) ─────────────────────────
// style: 'services' → multi-select service picker, bookable.
//        'project'  → free-text scope, always quote-first.
const V2_WORK = {
  homeowner: [
    { key: 'service',  label: 'Service & Repairs',     sub: 'Fix, replace, or install',    style: 'services' },
    { key: 'remodel',  label: 'Remodel',               sub: 'Renovation or upgrade',       style: 'project'  },
    { key: 'newconst', label: 'New Construction',      sub: 'Custom build or addition',    style: 'project'  },
  ],
  landlord: [
    { key: 'service',  label: 'Service & Repairs',     sub: 'Tenant issue or repair',      style: 'services' },
    { key: 'makeready',label: 'Make-Ready / Turnover', sub: 'Between tenants',             style: 'services' },
    { key: 'remodel',  label: 'Remodel',               sub: 'Unit renovation',             style: 'project'  },
  ],
  agent: [
    { key: 'service',  label: 'Listing Repairs',       sub: 'Inspection items & repairs',  style: 'services' },
  ],
  builder: [
    { key: 'service',  label: 'Punch-Out / Warranty',  sub: 'Service on your builds',      style: 'services' },
    { key: 'remodel',  label: 'Remodel',               sub: 'Renovation project',          style: 'project'  },
    { key: 'newconst', label: 'New Construction',      sub: 'Ground-up build',             style: 'project'  },
  ],
  business: [
    { key: 'service',  label: 'Service & Repairs',     sub: 'Fix, replace, or install',    style: 'services' },
    { key: 'remodel',  label: 'Build-Out / Remodel',   sub: 'Tenant improvement',          style: 'project'  },
    { key: 'newconst', label: 'New Construction',      sub: 'Ground-up build',             style: 'project'  },
  ],
};

// ── SERVICES (multi-select) ────────────────────────────────
// hours drives the scheduling window; quoteOnly work is never booked blind.
// customers (optional) restricts a service to specific personas.
const V2_SERVICES = [
  { key: 'inspection', label: 'Inspection Review & Bid',    sub: 'Itemized bid from the report',    icon: 'doc',    quoteOnly: true, customers: ['agent'], segments: ['residential', 'multi', 'commercial'] },
  { key: 'trouble',    label: 'Troubleshooting & Repair',   sub: "Something's not working right",   icon: 'wrench', hours: 2, segments: ['residential', 'multi', 'commercial'] },
  { key: 'outlets',    label: 'Outlets & Switches',         sub: 'Add, replace, upgrade, GFCI',     icon: 'outlet', hours: 2, segments: ['residential', 'multi', 'commercial'] },
  { key: 'fan',        label: 'Ceiling Fans',               sub: 'Install or replace',              icon: 'fan',    hours: 2, segments: ['residential', 'multi', 'commercial'] },
  { key: 'surge',      label: 'Surge Protection',           sub: 'Whole-property protection',       icon: 'surge',  hours: 2, segments: ['residential', 'multi', 'commercial'] },
  { key: 'lighting',   label: 'Lighting',                   sub: 'Recessed, fixtures, custom',      icon: 'light',  hours: 4, segments: ['residential', 'multi', 'commercial'] },
  { key: 'ev',         label: 'EV Charger',                 sub: 'Level 2 charger install',         icon: 'ev',     hours: 4, segments: ['residential', 'multi', 'commercial'] },
  { key: 'sauna',      label: 'Sauna Wiring',               sub: 'Dedicated circuit & heater wiring', icon: 'sauna', hours: 4, segments: ['residential', 'multi', 'commercial'] },
  { key: 'panel',      label: 'Panel Upgrade',              sub: 'Service replacement & upgrade',   icon: 'panel',  hours: 8, segments: ['residential', 'multi', 'commercial'] },
  { key: 'rewire',     label: 'Rewiring',                   sub: 'Whole or partial rewires',        icon: 'rewire', quoteOnly: true, segments: ['residential', 'multi', 'commercial'] },
  { key: 'generator',  label: 'Generator',                  sub: 'Backup power install',            icon: 'gen',    quoteOnly: true, segments: ['residential', 'multi', 'commercial'] },
  { key: 'other',      label: 'Something Else',             sub: "Tell us what's going on",         icon: 'more',   quoteOnly: true, segments: ['residential', 'multi', 'commercial'] },
];

function v2ServicesFor(customerType, propertyType) {
  return V2_SERVICES.filter(s =>
    s.segments.includes(propertyType) && (!s.customers || s.customers.includes(customerType))
  );
}

function v2SelectedServices(data) {
  return V2_SERVICES.filter(s => data.services.includes(s.key));
}

function v2HoursBadge(s) {
  if (s.quoteOnly) return 'Quote first';
  if (s.hours >= 8) return 'Full day';
  return `~${s.hours} hrs`;
}

// ── SCHEDULING WINDOWS ─────────────────────────────────────
// Selected services sum to hours; hours map to a window kind; window
// availability is derived from the base 2-hour crew slots in SLOTS.
const V2_WINDOWS = {
  '2h': [
    { label: '8 AM–10 AM',         start: 8,  end: 10, needs: ['8 AM–10 AM'] },
    { label: '10 AM–12 PM',        start: 10, end: 12, needs: ['10 AM–12 PM'] },
    { label: '1 PM–3 PM',          start: 13, end: 15, needs: ['1 PM–3 PM'] },
    { label: '3 PM–5 PM',          start: 15, end: 17, needs: ['3 PM–5 PM'] },
  ],
  half: [
    { label: 'Morning · 8 AM–12 PM',   start: 8,  end: 12, needs: ['8 AM–10 AM', '10 AM–12 PM'] },
    { label: 'Afternoon · 1 PM–5 PM',  start: 13, end: 17, needs: ['1 PM–3 PM', '3 PM–5 PM'] },
  ],
  full: [
    { label: 'Full Day · 8 AM–5 PM',   start: 8,  end: 17, needs: ['8 AM–10 AM', '10 AM–12 PM', '1 PM–3 PM', '3 PM–5 PM'] },
  ],
};
const V2_KIND_LABEL = { '2h': '2-hour window', half: 'half-day window', full: 'full-day visit' };

function v2WindowKind(hours) {
  if (hours <= 2) return '2h';
  if (hours <= 4) return 'half';
  return 'full';
}

function v2WindowsForDay(day, kind) {
  // CRITICAL (design §4): a half/full-day window's availability is single-tech
  // CONTINUITY, carried in the feed's `aggregates` — it must be read DIRECTLY,
  // never DERIVED from base slots (two techs each covering half a day would
  // falsely show the half-day open). When the real Volt feed is present it
  // attaches `aggregates`; for the mock fallback (base slots only) we derive.
  const aggs = day.aggregates;
  return V2_WINDOWS[kind].map(w => {
    if (kind !== '2h' && Array.isArray(aggs)) {
      const a = aggs.find(x => x.label === w.label);
      return { ...w, open: !!a && a.avail !== 'full' };
    }
    return {
      ...w,
      open: w.needs.every(n => {
        const s = (day.slots || []).find(x => x.label === n);
        return !!s && s.avail !== 'full';
      }),
    };
  });
}

// Booking eligibility — the single source of truth the schedule + confirm steps read.
function v2BookingInfo(data) {
  const work = (V2_WORK[data.customerType] || []).find(w => w.key === data.workType);
  const isProject = work?.style === 'project';
  const selected = v2SelectedServices(data);
  const quoteOnlyPicks = selected.filter(s => s.quoteOnly);
  const totalHours = selected.reduce((a, s) => a + (s.hours || 0), 0);
  const bookable = !isProject && selected.length > 0 && quoteOnlyPicks.length === 0;
  return { work, isProject, selected, quoteOnlyPicks, totalHours, kind: v2WindowKind(totalHours), bookable };
}

function v2QuoteNumber() {
  return `YJ-Q-2026-${Math.floor(1000 + Math.random() * 9000)}`;
}

// ── MOBILE HOOK ────────────────────────────────────────────
function useIsMobileV2() {
  const [m, setM] = React.useState(() => window.matchMedia('(max-width: 640px)').matches);
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 640px)');
    const fn = e => setM(e.matches);
    mq.addEventListener('change', fn);
    return () => mq.removeEventListener('change', fn);
  }, []);
  return m;
}

// ── SHARED UI ──────────────────────────────────────────────
const v2Label = { display: 'block', fontWeight: 700, fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: SG.gray, marginBottom: 6, fontFamily: 'Barlow Condensed' };
const v2Input = {
  width: '100%', padding: '13px 14px', fontFamily: 'Barlow Condensed', fontSize: 16, fontWeight: 600,
  color: SG.navy, background: '#fff', border: `1.5px solid ${SG.grayLight}`, borderRadius: 4, outline: 'none',
  transition: 'border-color 150ms', boxSizing: 'border-box',
};
const v2Eyebrow = { fontWeight: 800, fontSize: 11, letterSpacing: '0.18em', color: SG.gold, textTransform: 'uppercase', marginBottom: 10, fontFamily: 'Barlow Condensed' };

function V2StepHeader({ num, eyebrow, title, sub }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <h2 style={{ fontFamily: 'Barlow Condensed', fontWeight: 900, fontSize: 'clamp(24px, 6vw, 32px)', textTransform: 'uppercase', color: SG.navy, margin: 0, letterSpacing: '-0.01em', lineHeight: 1.05 }}>{title}</h2>
      {sub && <p style={{ fontFamily: 'Barlow Condensed', fontSize: 15, fontWeight: 500, color: SG.gray, margin: '8px 0 0', lineHeight: 1.45, textWrap: 'pretty' }}>{sub}</p>}
    </div>
  );
}

// Single-select choice card — 56px+ tap target
function V2Choice({ active, onClick, label, sub }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', padding: '13px 16px', borderRadius: 4, cursor: 'pointer', width: '100%',
      background: active ? SG.navy : '#fff',
      border: active ? `2px solid ${SG.gold}` : `1.5px solid ${SG.grayLight}`,
      color: active ? '#fff' : SG.navy, fontFamily: 'Barlow Condensed',
      minHeight: 56, transition: 'all 150ms ease',
    }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.borderColor = SG.gold; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.borderColor = SG.grayLight; }}>
      <div style={{ fontWeight: 800, fontSize: 14, textTransform: 'uppercase', letterSpacing: '0.04em', lineHeight: 1.2 }}>{label}</div>
      {sub && <div style={{ fontSize: 12, opacity: 0.65, marginTop: 2, lineHeight: 1.3, fontWeight: 600 }}>{sub}</div>}
    </button>
  );
}

// Multi-select service card with checkbox + duration badge
function V2ServiceCard({ active, onClick, service, quoteOnly }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', padding: '11px 12px', borderRadius: 4, cursor: 'pointer', width: '100%',
      background: active ? SG.navy : '#fff',
      border: active ? `2px solid ${SG.gold}` : `1.5px solid ${SG.grayLight}`,
      color: active ? '#fff' : SG.navy, fontFamily: 'Barlow Condensed',
      display: 'flex', alignItems: 'center', gap: 10, minHeight: 60, transition: 'all 150ms ease',
    }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.borderColor = SG.gold; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.borderColor = SG.grayLight; }}>
      <div style={{
        flexShrink: 0, width: 20, height: 20, borderRadius: 3,
        border: active ? `1.5px solid ${SG.gold}` : `1.5px solid ${SG.grayLight}`,
        background: active ? SG.gold : '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {active && <svg width="12" height="12" viewBox="0 0 12 12"><path d="M2 6l2.5 2.5L10 3" stroke={SG.navy} strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </div>
      <div style={{
        flexShrink: 0, width: 32, height: 32, borderRadius: 4,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: active ? 'rgba(245,166,35,0.15)' : 'rgba(27,42,74,0.06)',
      }}>
        {service.icon === 'doc'
          ? <svg width="17" height="17" viewBox="0 0 32 32" fill="none"><path d="M9 4h10l6 6v18H9z" stroke={active ? SG.gold : SG.navy} strokeWidth="1.8" strokeLinejoin="round"/><path d="M19 4v6h6" stroke={active ? SG.gold : SG.navy} strokeWidth="1.8" strokeLinejoin="round"/><line x1="13" y1="16" x2="21" y2="16" stroke={active ? SG.gold : SG.navy} strokeWidth="1.8" strokeLinecap="round"/><line x1="13" y1="21" x2="21" y2="21" stroke={active ? SG.gold : SG.navy} strokeWidth="1.8" strokeLinecap="round"/></svg>
          : <ServiceIcon kind={service.icon} color={active ? SG.gold : SG.navy} size={17} />}
      </div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontWeight: 800, fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.03em', lineHeight: 1.25 }}>{service.label}</div>
        <div style={{ fontSize: 11, opacity: 0.65, lineHeight: 1.3, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{service.sub}</div>
      </div>
      <div style={{
        flexShrink: 0, fontSize: 10, fontWeight: 800, letterSpacing: '0.08em', textTransform: 'uppercase',
        padding: '3px 7px', borderRadius: 3,
        background: (quoteOnly || service.quoteOnly) ? (active ? 'rgba(245,166,35,0.2)' : 'rgba(27,42,74,0.07)') : 'transparent',
        border: (quoteOnly || service.quoteOnly) ? 'none' : `1px solid ${active ? 'rgba(255,255,255,0.25)' : SG.grayLight}`,
        color: active ? SG.gold : ((quoteOnly || service.quoteOnly) ? SG.navy : SG.gray),
      }}>
        {quoteOnly ? 'Quote First' : v2HoursBadge(service)}
      </div>
    </button>
  );
}

Object.assign(window, {
  V2_CUSTOMERS, V2_PROPS, V2_PROPS_BY_CUSTOMER, V2_WORK, V2_SERVICES,
  v2ServicesFor, v2SelectedServices, v2HoursBadge,
  V2_WINDOWS, V2_KIND_LABEL, v2WindowKind, v2WindowsForDay, v2BookingInfo, v2QuoteNumber,
  useIsMobileV2, v2Label, v2Input, v2Eyebrow, V2StepHeader, V2Choice, V2ServiceCard,
});
