/* global React, Icons, AZ_DATA, Topbar, OrderSummary, SubmitModal,
   ChecklistVariant, IntegrationPicker */

const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "mode": "closer",
  "chipStyle": "pill"
}/*EDITMODE-END*/;

function useTweaks(defaults) {
  const [tweaks, setTweaks] = useState(defaults);
  function setTweak(keyOrObj, value) {
    const next = typeof keyOrObj === 'object'
      ? { ...tweaks, ...keyOrObj }
      : { ...tweaks, [keyOrObj]: value };
    setTweaks(next);
    try {
      window.parent.postMessage(
        { type: '__edit_mode_set_keys', edits: typeof keyOrObj === 'object' ? keyOrObj : { [keyOrObj]: value } },
        '*'
      );
    } catch (e) {}
  }
  return [tweaks, setTweak];
}

function App() {
  const { STANDARD, APPOINTMENT_MGMT, SALON_PACK, SYSTEM, INTEGRATION_CATALOG, BUSINESS, PRICING } = AZ_DATA;
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useState(false);

  // Apply theme to body
  useEffect(() => {
    document.body.setAttribute('data-theme', tweaks.theme || 'dark');
  }, [tweaks.theme]);

  // State: enabled scenario ids
  const [enabledIds, setEnabledIds] = useState(() => {
    const ids = [];
    STANDARD.forEach((s) => s.defaultOn && ids.push(s.id));
    SALON_PACK.forEach((s) => s.defaultOn && ids.push(s.id));
    SYSTEM.forEach((s) => ids.push(s.id)); // always on
    return ids;
  });

  // ---------- Integration state (per category) ----------
  // The user picks ONE integration per category they need. Defaults reflect the
  // pre-filled context (Square Appointments already connected, AgentZap built-in SMS).
  const [selectedIntegrations, setSelectedIntegrations] = useState({
    calendar: 'square',
    sms: 'agentzap_sms',
    // crm + pos start unset — added on first enable
  });

  // Modal state for integration picker:
  // { category, contextLabel, onPick }
  const [pickerState, setPickerState] = useState(null);

  function openPicker(category, contextLabel) {
    setPickerState({ category, contextLabel });
  }
  function pickIntegration(integrationId) {
    setSelectedIntegrations((cur) => ({ ...cur, [pickerState.category]: integrationId }));
  }

  // Custom scenarios (user free-form input, $200 one-time each, pending review)
  const [customScenarios, setCustomScenarios] = useState([]);
  function addCustom(text) {
    setCustomScenarios((cur) => [...cur, { id: `cust-${Date.now()}`, text, status: 'pending' }]);
  }
  function removeCustom(id) {
    setCustomScenarios((cur) => cur.filter((c) => c.id !== id));
  }

  const [modalOpen, setModalOpen] = useState(false);

  function toggle(id) {
    setEnabledIds((cur) => cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]);
  }

  // Appointment management is sold as a single module — toggle all 4 ids together.
  function toggleApptMgmt() {
    const apptIds = APPOINTMENT_MGMT.map((s) => s.id);
    setEnabledIds((cur) => {
      const anyOn = apptIds.some((id) => cur.includes(id));
      if (anyOn) return cur.filter((id) => !apptIds.includes(id));
      return [...cur, ...apptIds];
    });
  }

  // ----- Edit mode wiring -----
  useEffect(() => {
    function onMsg(e) {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    }
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // ---------- Computed totals ----------
  const allScn = useMemo(() => [...STANDARD, ...APPOINTMENT_MGMT, ...SALON_PACK, ...SYSTEM], []);
  const enabledScn = allScn.filter((s) => enabledIds.includes(s.id));

  // Salon pack subtotal (only salon pack items have basePrice)
  const salonSubtotal = SALON_PACK
    .filter((s) => enabledIds.includes(s.id))
    .reduce((sum, s) => sum + (s.basePrice || 0), 0);

  // Appointment management bundle price
  const apptMgmtIds = APPOINTMENT_MGMT.map((s) => s.id);
  const apptMgmtOn = apptMgmtIds.some((id) => enabledIds.includes(id));
  const apptMgmtSubtotal = apptMgmtOn ? PRICING.apptMgmtBundle : 0;

  // Custom scenarios subtotal
  const customSubtotal = customScenarios.length * PRICING.customScenario;

  // Integrations: which categories are required by the active configuration?
  const requiredCategories = useMemo(() => {
    const cats = new Set();
    enabledScn.forEach((s) => { if (s.integrationCategory) cats.add(s.integrationCategory); });
    return cats;
  }, [enabledScn]);

  // For each required category, look up selected integration's price (unique per category).
  const integrationsForSummary = useMemo(() => {
    return Array.from(requiredCategories)
      .map((cat) => {
        const id = selectedIntegrations[cat];
        if (!id) return { category: cat, integration: null };
        return { category: cat, integration: INTEGRATION_CATALOG.find((i) => i.id === id) };
      });
  }, [requiredCategories, selectedIntegrations]);

  const integrationsSubtotal = integrationsForSummary.reduce(
    (sum, x) => sum + (x.integration?.price || 0),
    0
  );

  const grandTotal = PRICING.base
    + salonSubtotal
    + apptMgmtSubtotal
    + customSubtotal
    + integrationsSubtotal;

  const totalScenarioCount =
    enabledScn.filter((s) => !s.system).length +
    customScenarios.length;

  return (
    <div>
      <Topbar step="scenarios" mode={tweaks.mode} percentComplete={62} />

      <div className="layout">
        {/* MAIN COLUMN */}
        <main>
          <div className="section-eyebrow">Step 04 of 09 · The heart of your build</div>
          <h1 className="section-title">Which calls should your <em>agent</em> handle?</h1>
          <p className="section-sub">
            Pick the scenarios your AI receptionist will know how to navigate. For each capability, choose the integration that powers it — calendar, SMS, CRM, POS. Every choice updates your total.
          </p>

          {/* Context strip */}
          <div className="context-strip">
            <div className="ind-icon"><Icons.Sparkle size={18} /></div>
            <div className="context-strip-body">
              <div className="context-strip-title">{BUSINESS.name} · {BUSINESS.industry}</div>
              <div className="context-strip-meta">{BUSINESS.locations} · {BUSINESS.contact} · Square Appointments connected</div>
            </div>
            <span className="context-strip-pill">Playbook loaded</span>
          </div>

          <ChecklistVariant
            enabledIds={enabledIds}
            toggle={toggle}
            toggleApptMgmt={toggleApptMgmt}
            mode={tweaks.mode === 'self' ? 'self' : 'closer'}
            customScenarios={customScenarios}
            addCustom={addCustom}
            removeCustom={removeCustom}
            selectedIntegrations={selectedIntegrations}
            openPicker={openPicker}
            chipStyle={tweaks.chipStyle || 'pill'}
          />

          {/* Page footer / step nav */}
          <div className="page-foot">
            <button className="page-foot-back">
              <Icons.Arrow size={14} style={{ transform: 'rotate(180deg)' }} />
              Back to Voice &amp; persona
            </button>
            <div className="page-foot-actions">
              <div className="page-foot-meta">{totalScenarioCount} scenarios · ${grandTotal.toLocaleString()} one-time</div>
              <button className="btn btn-ghost">Save &amp; finish later</button>
              <button className="btn btn-primary" onClick={() => setModalOpen(true)}>
                Continue to phone setup
                <Icons.Arrow size={14} />
              </button>
            </div>
          </div>
        </main>

        {/* SIDEBAR */}
        <OrderSummary
          enabledIds={enabledIds}
          customScenarios={customScenarios}
          integrationsForSummary={integrationsForSummary}
          onCheckout={() => setModalOpen(true)}
        />
      </div>

      {modalOpen && (
        <SubmitModal
          enabledIds={enabledIds}
          customScenarios={customScenarios}
          integrationsForSummary={integrationsForSummary}
          total={grandTotal}
          onClose={() => setModalOpen(false)}
        />
      )}

      {pickerState && (
        <IntegrationPicker
          category={pickerState.category}
          currentId={selectedIntegrations[pickerState.category]}
          contextLabel={pickerState.contextLabel}
          onPick={pickIntegration}
          onClose={() => setPickerState(null)}
        />
      )}

      {tweaksOpen && (
        <TweaksPanel
          tweaks={tweaks}
          setTweak={setTweak}
          onClose={() => {
            setTweaksOpen(false);
            try { window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*'); } catch (e) {}
          }}
        />
      )}
    </div>
  );
}

// ---------- Tweaks panel ----------
function TweaksPanel({ tweaks, setTweak, onClose }) {
  const themeOptions = [
    {
      value: 'dark',
      label: 'Dark SaaS',
      sub: 'Matches agentzap.ai',
      swatch: ['#1A1210', '#2A1D15', '#E8612D'],
    },
    {
      value: 'cream',
      label: 'Cream editorial',
      sub: 'Warm parchment, burnt orange',
      swatch: ['#F5F0E6', '#FDF6ED', '#C0511A'],
    },
    {
      value: 'hybrid',
      label: 'Hybrid',
      sub: 'Cream form, dark chrome',
      swatch: ['#F5F0E6', '#1A1210', '#E8612D'],
    },
  ];

  return (
    <div className="tweaks-panel">
      <div className="tweaks-head">
        <div className="tweaks-title">Tweaks</div>
        <button onClick={onClose} className="tweaks-close">✕</button>
      </div>
      <div className="tweaks-body">
        <div className="tweak-section">
          <div className="tweak-label">Theme</div>
          <div className="tweak-themes">
            {themeOptions.map((t) => (
              <button
                key={t.value}
                onClick={() => setTweak('theme', t.value)}
                className={`tweak-theme ${tweaks.theme === t.value ? 'on' : ''}`}
              >
                <div className="tweak-theme-swatch">
                  {t.swatch.map((c, i) => (
                    <span key={i} style={{ background: c }}></span>
                  ))}
                </div>
                <div className="tweak-theme-text">
                  <div className="tweak-theme-name">{t.label}</div>
                  <div className="tweak-theme-sub">{t.sub}</div>
                </div>
                <div className="tweak-theme-radio">
                  {tweaks.theme === t.value && <Icons.Check size={11} strokeWidth={3} />}
                </div>
              </button>
            ))}
          </div>
        </div>

        <div className="tweak-section">
          <div className="tweak-label">User mode</div>
          <div className="tweak-segment">
            {[
              { value: 'closer', label: 'Closer-led' },
              { value: 'self', label: 'Self-serve' },
            ].map((o) => (
              <button
                key={o.value}
                onClick={() => setTweak('mode', o.value)}
                className={tweaks.mode === o.value ? 'on' : ''}
              >
                {o.label}
              </button>
            ))}
          </div>
        </div>

        <div className="tweak-section">
          <div className="tweak-label">Integration chip style</div>
          <div className="tweak-chip-styles">
            {[
              { value: 'pill',    label: 'Pill',    sub: 'Full label + logo + price' },
              { value: 'compact', label: 'Compact', sub: 'Logo + name + price' },
              { value: 'inline',  label: 'Inline',  sub: 'Text only — no border' },
              { value: 'card',    label: 'Card',    sub: 'Stacked, more visual' },
            ].map((o) => (
              <button
                key={o.value}
                onClick={() => setTweak('chipStyle', o.value)}
                className={`tweak-chip-style ${tweaks.chipStyle === o.value ? 'on' : ''}`}
              >
                <div className="tweak-chip-style-preview">
                  <ChipPreview style={o.value} />
                </div>
                <div className="tweak-chip-style-text">
                  <div className="tweak-chip-style-name">{o.label}</div>
                  <div className="tweak-chip-style-sub">{o.sub}</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ChipPreview({ style }) {
  if (style === 'inline') {
    return (
      <span className="chip-preview-inline">
        <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
        Powered by <b>Vagaro</b> · +$400
      </span>
    );
  }
  if (style === 'compact') {
    return (
      <span className="chip-preview-compact">
        <span className="chip-preview-logo">Va</span>
        Vagaro
        <span style={{ color: 'var(--orange)', fontWeight: 600 }}>+$400</span>
      </span>
    );
  }
  if (style === 'card') {
    return (
      <span className="chip-preview-card">
        <span className="chip-preview-logo">Va</span>
        <span className="chip-preview-card-body">
          <span className="chip-preview-card-cat">CALENDAR</span>
          <span>Vagaro</span>
        </span>
        <span style={{ color: 'var(--orange)', fontWeight: 600, marginLeft: 'auto' }}>+$400</span>
      </span>
    );
  }
  // pill (default)
  return (
    <span className="chip-preview-pill">
      <span className="chip-preview-cat">CAL</span>
      <span className="chip-preview-bar"></span>
      <span className="chip-preview-logo">Va</span>
      Vagaro
      <span style={{ color: 'var(--orange)', fontWeight: 600 }}>+$400</span>
    </span>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
