/* global React, Icons, AZ_DATA */
// Right sticky sidebar — running total (one-time, no recurring).

const { useState: useStateSum, useEffect: useEffectSum, useRef: useRefSum } = React;

function OrderSummary({ enabledIds, customScenarios, integrationsForSummary, onCheckout }) {
  const { STANDARD, APPOINTMENT_MGMT, SALON_PACK, SYSTEM, PRICING, BUSINESS, CATEGORY_LABELS } = AZ_DATA;

  const allScn = [...STANDARD, ...APPOINTMENT_MGMT, ...SALON_PACK, ...SYSTEM];
  const enabledScn = allScn.filter((s) => enabledIds.includes(s.id));
  const apptOn = enabledScn.filter((s) => APPOINTMENT_MGMT.some((x) => x.id === s.id));
  const salonOn = enabledScn.filter((s) => SALON_PACK.some((x) => x.id === s.id));
  const standardOn = enabledScn.filter((s) => STANDARD.some((x) => x.id === s.id));
  const customs = customScenarios || [];
  const customSubtotal = customs.length * PRICING.customScenario;

  const integForSum = integrationsForSummary || [];
  const salonSubtotal = salonOn.reduce((sum, s) => sum + (s.basePrice || 0), 0);
  const integSubtotal = integForSum.reduce((sum, x) => sum + (x.integration?.price || 0), 0);
  const apptMgmtOn = apptOn.length > 0;
  const apptMgmtSubtotal = apptMgmtOn ? PRICING.apptMgmtBundle : 0;
  const grandTotal = PRICING.base + salonSubtotal + integSubtotal + customSubtotal + apptMgmtSubtotal;

  // Animate total on change
  const totalRef = useRefSum(null);
  const lastTotalRef = useRefSum(grandTotal);
  useEffectSum(() => {
    if (lastTotalRef.current !== grandTotal && totalRef.current) {
      totalRef.current.classList.remove('bump');
      void totalRef.current.offsetWidth;
      totalRef.current.classList.add('bump');
    }
    lastTotalRef.current = grandTotal;
  }, [grandTotal]);

  return (
    <aside className="summary" data-screen-label="Order summary sidebar">
      <div className="summary-head">
        <div className="summary-eyebrow">Your order</div>
        <div className="summary-business">{BUSINESS.name}</div>
        <div className="summary-business-meta">{BUSINESS.industry} · {BUSINESS.locations}</div>
      </div>

      <div className="summary-body">
        {/* Base plan */}
        <div className="summary-section">
          <div className="summary-section-head">
            <span>Base plan</span>
            <span>One-time</span>
          </div>
          <div className="summary-line">
            <span className="summary-line-name">
              AgentZap Voice
              <span className="dim"> phone number + agent</span>
            </span>
            <span className="summary-line-price">${PRICING.base}</span>
          </div>
        </div>

        {/* Standard scenarios — collapsed line */}
        {standardOn.length > 0 &&
        <div className="summary-section">
            <div className="summary-section-head">
              <span>Standard scenarios</span>
              <span>{standardOn.length} of {STANDARD.length}</span>
            </div>
            <div className="summary-line">
              <span className="summary-line-name">Included with base plan</span>
              <span className="summary-line-price zero">Included</span>
            </div>
          </div>
        }

        {/* Appointment management — sold as one module */}
        {apptMgmtOn &&
        <div className="summary-section">
            <div className="summary-section-head">
              <span>Appointment management</span>
              <span>Module</span>
            </div>
            <div className="summary-line">
              <span className="summary-line-name">Bundle <span className="dim">all {APPOINTMENT_MGMT.length} scenarios</span></span>
              <span className="summary-line-price">+${PRICING.apptMgmtBundle}</span>
            </div>
            {apptOn.map((s) =>
          <div className="summary-sub-line" key={s.id}>
                <Icons.Check size={9} strokeWidth={3} />
                {shortName(s.name)}
              </div>
          )}
          </div>
        }

        {/* Salon pack — itemized */}
        {salonOn.length > 0 &&
        <div className="summary-section">
            <div className="summary-section-head">
              <span>Salon pack</span>
              <span>{salonOn.length} added</span>
            </div>
            {salonOn.map((s) =>
          <div className="summary-line" key={s.id}>
                <span className="summary-line-name">{shortName(s.name)}</span>
                <span className="summary-line-price">+${s.basePrice}</span>
              </div>
          )}
          </div>
        }

        {/* Integrations — one per required category */}
        {integForSum.length > 0 &&
        <div className="summary-section">
            <div className="summary-section-head">
              <span>Integrations</span>
              <span>{integForSum.length} chosen</span>
            </div>
            {integForSum.map(({ category, integration }) =>
          <div className="summary-line" key={category}>
                <span className="summary-line-name">
                  {integration ? integration.name : '— pick one —'}
                  <span className="dim"> {CATEGORY_LABELS[category]?.toLowerCase()}</span>
                </span>
                <span className={`summary-line-price ${integration?.price === 0 ? 'zero' : ''}`}>
                  {integration ?
              integration.price === 0 ? 'Included' : `+$${integration.price.toLocaleString()}` :
              'Choose'}
                </span>
              </div>
          )}
          </div>
        }

        {/* Custom scenarios */}
        {customs.length > 0 &&
        <div className="summary-section">
            <div className="summary-section-head">
              <span>Custom · pending review</span>
              <span>{customs.length}</span>
            </div>
            {customs.map((c) =>
          <div className="summary-line" key={c.id}>
                <span className="summary-line-name">
                  <span className="summary-pending-dot"></span>
                  {shortName(firstSentence(c.text))}
                </span>
                <span className="summary-line-price">+${PRICING.customScenario}</span>
              </div>
          )}
            <div className="summary-custom-note">
              <Icons.Alert size={11} />
              <span>
                The ${PRICING.customScenario}/scenario fee is charged <b>only after</b> our engineering team confirms feasibility. If not buildable, the line is dropped.
              </span>
            </div>
          </div>
        }
      </div>

      <div className="summary-grand">
        <div>
          <div className="summary-grand-label">Total · one-time</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>
            ${PRICING.base} base
            {apptMgmtSubtotal > 0 && <> + ${apptMgmtSubtotal} module</>}
            {salonSubtotal > 0 && <> + ${salonSubtotal} salon</>}
            {integSubtotal > 0 && <> + ${integSubtotal.toLocaleString()} integ.</>}
            {customSubtotal > 0 && <> + ${customSubtotal} custom</>}
          </div>
        </div>
        <div className="summary-grand-value" ref={totalRef} style={{ fontWeight: "600", letterSpacing: "-5px" }}>
          ${grandTotal.toLocaleString()}
        </div>
      </div>

      <div className="summary-cta">
        <button className="btn btn-primary" onClick={onCheckout}>
          Review &amp; submit
          <Icons.Arrow size={16} />
        </button>
      </div>

      <div className="summary-trust">
        <div className="summary-trust-row">
          <Icons.Check size={14} strokeWidth={2.5} />
          30-day money-back guarantee
        </div>
        <div className="summary-trust-row">
          <Icons.Check size={14} strokeWidth={2.5} />
          Launch in 5 business days
        </div>
        <div className="summary-trust-row">
          <Icons.Lock size={14} strokeWidth={2.5} />
          One-time purchase — no recurring charges
        </div>
      </div>
    </aside>);

}

// Shorten long names for sidebar lines
function shortName(n) {
  if (n.length > 38) return n.slice(0, 36).trim() + '…';
  return n;
}
function firstSentence(text) {
  const t = text.trim();
  const m = t.match(/^[^.!?\n]{1,80}/);
  return m ? m[0] : t.slice(0, 80);
}

window.OrderSummary = OrderSummary;