/* Snack Overflow — Main App (Production) */
const { useState, useCallback, useMemo, useEffect } = React;

function App() {
  /* ── Tweaks ─────────────────────────────────── */
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const accent = t.accentColor;

  /* ── Core state ─────────────────────────────── */
  const [screen, setScreen]             = useState("shop");
  const [cart, setCart]                  = useState({});
  const [configCart, setConfigCart]      = useState([]);
  const [configuring, setConfiguring]   = useState(null);
  const [checkoutItems, setCheckoutItems] = useState([]);
  const [checkoutTotal, setCheckoutTotal] = useState(0);
  const [selPerson, setSelPerson]       = useState(null);
  const [showConfirm, setShowConfirm]   = useState(false);
  const [showSuccess, setShowSuccess]   = useState(false);
  const [submitting, setSubmitting]     = useState(false);
  const [tabTotal, setTabTotal]         = useState(0);
  const [newTabTotal, setNewTabTotal]   = useState(0);

  /* ── Car wash state ─────────────────────────── */
  const [cwBooking, setCwBooking]         = useState(null);
  const [cwPerson, setCwPerson]           = useState(null);
  const [showCwConfirm, setShowCwConfirm] = useState(false);
  const [showCwSuccess, setShowCwSuccess] = useState(false);
  const [cwTab, setCwTab]                 = useState(0);

  /* ── Cart helpers ───────────────────────────── */
  const addItem    = useCallback(id => setCart(p => ({ ...p, [id]: (p[id] || 0) + 1 })), []);
  const removeItem = useCallback(id => setCart(p => {
    const c = { ...p }; if (c[id] > 1) c[id]--; else delete c[id]; return c;
  }), []);
  const clearCart   = useCallback(() => { setCart({}); setConfigCart([]); }, []);

  /* ── Car wash helpers ────────────────────────── */
  const handleCarWash = useCallback(() => setScreen('carwash'), []);

  const handleCwBook = useCallback(booking => {
    setCwBooking(booking);
    setScreen('carwash-person');
  }, []);

  const handleCwSelectPerson = useCallback(async (name) => {
    setCwPerson(name);
    if (cwBooking && cwBooking.price > 0) {
      const empId = window.EMPLOYEE_ID_MAP[name];
      if (empId) {
        try {
          const data = await window.api.getEmployeeTab(empId);
          setCwTab(parseFloat(data.tab_total) || 0);
        } catch (err) { setCwTab(0); }
      } else { setCwTab(0); }
    } else { setCwTab(0); }
    setShowCwConfirm(true);
  }, [cwBooking]);

  const handleCwConfirm = useCallback(async () => {
    try {
      const empId = window.EMPLOYEE_ID_MAP[cwPerson];
      if (!empId) throw new Error('Employee not found');
      await CW.addBooking({
        employee_id: empId,
        employee: cwPerson,
        wash_type_id: cwBooking.washType.id,
        date: cwBooking.date,
        is_own_car: cwBooking.isOwnCar,
        vehicle_owner: cwBooking.vehicleOwner,
        price: cwBooking.price,
      });
      setShowCwConfirm(false);
      setShowCwSuccess(true);
    } catch (err) {
      alert('Car wash booking failed: ' + err.message);
    }
  }, [cwPerson, cwBooking]);

  const handleCwDismiss = useCallback(() => {
    setShowCwSuccess(false);
    setCwBooking(null);
    setCwPerson(null);
    setCwTab(0);
    setScreen('shop');
  }, []);

  const handleCwCancelConfirm = useCallback(() => {
    setShowCwConfirm(false);
    setCwPerson(null);
  }, []);

  /* ── Configurable item helpers ───────────────── */
  const handleConfigure = useCallback(item => {
    setConfiguring(item); setScreen("builder");
  }, []);

  const handleAddConfigured = useCallback(entry => {
    const uid = `cfg-${entry.itemId}-${Date.now()}`;
    setConfigCart(prev => [...prev, { ...entry, uid }]);
    setConfiguring(null); setScreen("shop");
  }, []);

  /* ── Flow handlers ──────────────────────────── */
  const handleCheckout = useCallback((rows, total) => {
    setCheckoutItems(rows); setCheckoutTotal(total); setScreen("person");
  }, []);

  const handleSelectPerson = useCallback(async (name) => {
    setSelPerson(name);
    // Fetch current tab from API
    const empId = window.EMPLOYEE_ID_MAP[name];
    if (empId) {
      try {
        const data = await window.api.getEmployeeTab(empId);
        setTabTotal(parseFloat(data.tab_total) || 0);
      } catch (err) {
        console.error('Failed to fetch tab:', err);
        setTabTotal(0);
      }
    } else {
      setTabTotal(0);
    }
    setShowConfirm(true);
  }, []);

  const handleConfirm = useCallback(async () => {
    if (submitting) return;
    setSubmitting(true);

    const empId = window.EMPLOYEE_ID_MAP[selPerson];
    if (!empId) {
      alert('Employee not found');
      setSubmitting(false);
      return;
    }

    // Build API payload
    const apiItems = checkoutItems.map(it => {
      if (it.configurable || (it.id && String(it.id).startsWith('cfg-'))) {
        // Configurable item — extract selected option IDs from summaryLines
        // The summaryLines store option names; we need IDs.
        // The cart stores selections which map step→option ID.
        // For configured items, we stored selections in configCart.
        // Find the matching configCart entry.
        const cfgEntry = configCart.find(c => c.uid === it.id);
        if (cfgEntry) {
          const selectedOptionIds = [];
          Object.values(cfgEntry.selections).forEach(sel => {
            if (Array.isArray(sel)) {
              sel.forEach(optId => selectedOptionIds.push(parseInt(optId)));
            } else if (sel !== null) {
              selectedOptionIds.push(parseInt(sel));
            }
          });
          return {
            product_id: cfgEntry.itemId,
            qty: it.qty,
            configured: true,
            selected_option_ids: selectedOptionIds,
            unit_price: it.price,
          };
        }
      }
      // Regular item
      return { product_id: it.id, qty: it.qty };
    });

    try {
      const result = await window.api.postTransaction({
        employee_id: empId,
        items: apiItems,
      });
      setNewTabTotal(parseFloat(result.tab_total) || (tabTotal + checkoutTotal));
      setShowConfirm(false);
      setShowSuccess(true);
    } catch (err) {
      console.error('Transaction failed:', err);
      alert('Transaction failed: ' + err.message);
    } finally {
      setSubmitting(false);
    }
  }, [selPerson, checkoutItems, checkoutTotal, configCart, submitting, tabTotal]);

  const handleDismiss = useCallback(() => {
    setShowSuccess(false); setCart({}); setConfigCart([]); setScreen("shop");
    setSelPerson(null); setCheckoutItems([]); setCheckoutTotal(0);
    setTabTotal(0); setNewTabTotal(0);
  }, []);

  const handleBack = useCallback(() => {
    if (screen === "person") setScreen("shop");
    if (screen === "builder") { setConfiguring(null); setScreen("shop"); }
    if (screen === "carwash") setScreen("shop");
    if (screen === "carwash-person") setScreen("carwash");
  }, [screen]);

  const handleCancelConfirm = useCallback(() => {
    setShowConfirm(false); setSelPerson(null);
  }, []);

  /* ── Pick notification component ────────────── */
  const SuccessComp = ({ Modal: SuccessModal, Toast: SuccessToast, "Full Screen": SuccessFullScreen })[t.notificationStyle] || SuccessModal;

  return (
    <div className="app">
      <Header screen={screen} onBack={handleBack} onCarWash={handleCarWash} accentColor={accent} />

      {screen === "shop" && <ShopScreen cart={cart} configCart={configCart} onAdd={addItem} onRemove={removeItem} onConfigure={handleConfigure} accent={accent} />}
      {screen === "builder" && configuring && <ConfigBuilder item={configuring} onAdd={handleAddConfigured} accent={accent} />}
      {screen === "carwash" && <CarWashScreen onBook={handleCwBook} accent={accent} />}
      {screen === "carwash-person" && (
        <PersonScreen items={[]} total={cwBooking ? cwBooking.price : 0}
          onSelect={handleCwSelectPerson} accent={accent}
          title="Who's booking?"
          subtitle={cwBooking ? `${cwBooking.washType.name} \u00b7 ${cwBooking.price === 0 ? 'Free' : 'R' + cwBooking.price.toFixed(2)}` : ''} />
      )}
      {screen === "person" && <PersonScreen items={checkoutItems} total={checkoutTotal} onSelect={handleSelectPerson} accent={accent} />}
      {screen === "shop" && <CartBar cart={cart} configCart={configCart} onCheckout={handleCheckout} onClear={clearCart} accent={accent} />}

      {showConfirm && (
        <ConfirmDialog person={selPerson} items={checkoutItems} total={checkoutTotal}
          tab={tabTotal} onConfirm={handleConfirm} onCancel={handleCancelConfirm} accent={accent}
          submitting={submitting} />
      )}

      {showCwConfirm && cwBooking && (
        <CarWashConfirm person={cwPerson} booking={cwBooking} tab={cwTab}
          onConfirm={handleCwConfirm} onCancel={handleCwCancelConfirm} accent={accent} />
      )}
      {showCwSuccess && cwBooking && (
        <CarWashSuccess person={cwPerson} booking={cwBooking}
          onDismiss={handleCwDismiss} accent={accent} />
      )}

      {showSuccess && (
        <SuccessComp person={selPerson} items={checkoutItems} total={checkoutTotal}
          newTab={newTabTotal} onDismiss={handleDismiss} accent={accent} />
      )}

      <TweaksPanel>
        <TweakSection title="Appearance">
          <TweakColor label="Accent" value={t.accentColor}
            options={["#FFD600", "#4a4a4a", "#2563eb"]}
            onChange={v => setTweak("accentColor", v)} />
        </TweakSection>
        <TweakSection title="Notification Style">
          <TweakRadio label="After sale" value={t.notificationStyle}
            options={["Modal", "Toast", "Full Screen"]}
            onChange={v => setTweak("notificationStyle", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Mount only when data is loaded from API
function mount() {
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
}
if (window.SNACK_ITEMS) { mount(); }
else { window.addEventListener('data-ready', mount); }
