/* global React, Icons, AZ_DATA */
// Variant A — Checklist (grouped rows). Each scenario can carry an integration
// chip; click the chip to swap the integration that powers its category.

const { useState: useStateCL } = React;

function ChecklistVariant({
  enabledIds, toggle, toggleApptMgmt, mode,
  customScenarios, addCustom, removeCustom,
  selectedIntegrations, openPicker,
  chipStyle
}) {
  const { STANDARD, APPOINTMENT_MGMT, SALON_PACK, SYSTEM, PRICING } = AZ_DATA;

  const standardCount = STANDARD.filter((s) => enabledIds.includes(s.id)).length;
  const apptMgmtOn = APPOINTMENT_MGMT.some((s) => enabledIds.includes(s.id));
  const salonCount = SALON_PACK.filter((s) => enabledIds.includes(s.id)).length;
  const salonSubtotal = SALON_PACK.filter((s) => enabledIds.includes(s.id)).reduce((a, s) => a + s.basePrice, 0);
  const customSubtotal = (customScenarios?.length || 0) * PRICING.customScenario;

  function renderRow(scenario, on, onToggle, system) {
    return (
      <ChecklistRow
        key={scenario.id}
        scenario={scenario}
        on={on}
        onToggle={onToggle}
        system={system}
        selectedIntegrations={selectedIntegrations}
        openPicker={openPicker}
        chipStyle={chipStyle} />);


  }

  return (
    <div data-screen-label="Scenarios — checklist">
      {mode === 'self' &&
      <div className="help-bubble">
          <div className="help-bubble-icon"><Icons.Sparkle size={14} /></div>
          <div>
            <b>This is the most important step.</b> Each scenario your agent handles can be powered by an integration of your choosing — calendar, SMS, CRM, point-of-sale. We've defaulted to Square Appointments since that's already connected; you can swap to Vagaro, Booker, or any other supported system from each row.
          </div>
        </div>
      }

      {/* Standard library */}
      <div className="group-header">
        <div className="group-header-title">Standard library · works for any business</div>
        <div className="group-header-meta">
          <b>{standardCount}</b> of {STANDARD.length} enabled · Included in base
        </div>
      </div>
      {STANDARD.map((s) => renderRow(s, enabledIds.includes(s.id), () => toggle(s.id)))}

      {/* Appointment management — SOLD AS A BUNDLE */}
      <div className="group-header">
        <div className="group-header-title">
          Appointment management
          <span className="group-header-badge">Paid module</span>
        </div>
        <div className="group-header-meta">
          {apptMgmtOn ?
          <><b>Module enabled</b> · +${PRICING.apptMgmtBundle} one-time</> :
          <>One toggle · ${PRICING.apptMgmtBundle} one-time bundle</>}
        </div>
      </div>
      <ApptMgmtBundle
        items={APPOINTMENT_MGMT}
        on={apptMgmtOn}
        onToggle={toggleApptMgmt}
        price={PRICING.apptMgmtBundle}
        selectedIntegrations={selectedIntegrations}
        openPicker={openPicker}
        chipStyle={chipStyle} />
      

      {/* Salon pack */}
      <div className="group-header">
        <div className="group-header-title">Salon &amp; spa pack · loaded for your industry</div>
        <div className="group-header-meta">
          {salonCount > 0 ?
          <><b>{salonCount}</b> added · +${salonSubtotal} one-time</> :
          <>à la carte</>}
        </div>
      </div>
      {SALON_PACK.map((s) => renderRow(s, enabledIds.includes(s.id), () => toggle(s.id)))}

      {/* System */}
      <div className="group-header">
        <div className="group-header-title">Always on · the safety net</div>
        <div className="group-header-meta">Required · Included</div>
      </div>
      {SYSTEM.map((s) => renderRow(s, true, () => {}, true))}

      {/* Custom scenarios */}
      <div className="group-header">
        <div className="group-header-title">
          Custom scenarios
          <span className="group-header-badge subdued">Subject to review</span>
        </div>
        <div className="group-header-meta">
          {customScenarios?.length > 0 ?
          <><b>{customScenarios.length}</b> requested · +${customSubtotal} one-time</> :
          <>${PRICING.customScenario} one-time each</>}
        </div>
      </div>
      <div className="group-note">
        Describe a call your shop handles that the standard scenarios don't cover. Each one is reviewed by our AI engineers — if it's buildable in our platform, it lands in your batch. If not, we'll suggest the closest standard scenario and refund the line item.
      </div>

      {(customScenarios || []).map((c) =>
      <CustomScenarioRow key={c.id} scenario={c} onRemove={() => removeCustom(c.id)} />
      )}
      <CustomScenarioComposer onAdd={addCustom} pricing={PRICING.customScenario} count={customScenarios?.length || 0} />
    </div>);

}

function ChecklistRow({ scenario, on, onToggle, system, selectedIntegrations, openPicker, chipStyle }) {
  const cat = scenario.integrationCategory;
  return (
    <div className={`row ${on ? 'on' : ''} ${system ? 'system' : ''}`} onClick={onToggle}>
      <div className={`check ${on ? 'on' : ''}`}>
        <Icons.Check />
      </div>
      <div className="row-body">
        <div className="row-title">
          {scenario.name}
          {system && <span className="sys-tag">Required</span>}
        </div>
        <div className="row-desc">{scenario.desc}</div>
        {cat && on &&
        <IntegrationChip
          category={cat}
          currentId={selectedIntegrations[cat]}
          contextLabel={scenario.name}
          openPicker={openPicker}
          style={chipStyle} />

        }
      </div>
      <div className={`row-price ${scenario.basePrice === 0 ? 'included' : ''}`}>
        {scenario.basePrice === 0 ?
        'Included' :
        <>+${scenario.basePrice}<span className="row-price-suffix"> one-time</span></>}
      </div>
      <button className="row-edit" onClick={(e) => e.stopPropagation()} title="Edit defaults">
        <Icons.More size={16} />
      </button>
    </div>);

}

// ---------- Integration chip ----------
// `style` is one of: 'pill' (default — full label), 'compact' (logo + price),
// 'inline' (text-only, no border), or 'card' (card-style with more info).
function IntegrationChip({ category, currentId, contextLabel, openPicker, style }) {
  const { INTEGRATION_CATALOG, CATEGORY_LABELS } = AZ_DATA;
  const integ = currentId ? INTEGRATION_CATALOG.find((i) => i.id === currentId) : null;
  const catLabel = CATEGORY_LABELS[category] || category;
  const styleClass = `style-${style || 'pill'}`;

  function click(e) {
    e.stopPropagation();
    openPicker(category, contextLabel);
  }

  if (!integ) {
    return (
      <button className={`integration-chip empty ${styleClass}`} onClick={click}>
        <span className="integration-chip-icon"><Icons.Bolt size={10} /></span>
        Choose {catLabel.toLowerCase()}
        <Icons.Arrow size={10} />
      </button>);

  }

  if (style === 'inline') {
    return (
      <button className={`integration-chip ${styleClass}`} onClick={click} title="Click to change integration">
        <Icons.Bolt size={10} />
        Powered by <b>{integ.name}</b>
        <span className="integration-chip-divider"></span>
        <span className={`integration-chip-price ${integ.price === 0 ? 'zero' : ''}`}>
          {integ.price === 0 ? 'Free' : `+$${integ.price.toLocaleString()}`}
        </span>
      </button>);

  }

  if (style === 'compact') {
    return (
      <button className={`integration-chip ${styleClass}`} onClick={click} title={`Powered by ${integ.name}. Click to change.`}>
        <span className="integration-chip-logo">{integ.short}</span>
        <span className="integration-chip-name">{integ.name}</span>
        <span className={`integration-chip-price ${integ.price === 0 ? 'zero' : ''}`}>
          {integ.price === 0 ? 'Free' : `+$${integ.price.toLocaleString()}`}
        </span>
      </button>);

  }

  if (style === 'card') {
    return (
      <button className={`integration-chip ${styleClass}`} onClick={click} title="Click to change integration">
        <span className="integration-chip-logo">{integ.short}</span>
        <span className="integration-chip-card-body">
          <span className="integration-chip-card-cat">{category.toUpperCase()}</span>
          <span className="integration-chip-name">{integ.name}</span>
        </span>
        <span className="integration-chip-divider"></span>
        <span className={`integration-chip-price ${integ.price === 0 ? 'zero' : ''}`}>
          {integ.price === 0 ? 'Free' : `+$${integ.price.toLocaleString()}`}
        </span>
        <Icons.More size={11} />
      </button>);

  }

  // default: pill
  return (
    <button className={`integration-chip ${styleClass}`} onClick={click} title={`Powered by ${integ.name}. Click to change.`}>
      <span className="integration-chip-cat">{catLabel}</span>
      <span className="integration-chip-divider"></span>
      <span className="integration-chip-logo">{integ.short}</span>
      <span className="integration-chip-name">{integ.name}</span>
      <span className={`integration-chip-price ${integ.price === 0 ? 'zero' : ''}`}>
        {integ.price === 0 ? 'Free' : `+$${integ.price.toLocaleString()}`}
      </span>
    </button>);

}

// ---------- Appointment management bundle card ----------
function ApptMgmtBundle({ items, on, onToggle, price, selectedIntegrations, openPicker, chipStyle }) {
  return (
    <div className={`bundle-card ${on ? 'on' : ''}`}>
      <div className="bundle-card-head" onClick={onToggle}>
        <div className={`toggle big ${on ? 'on' : ''}`}></div>
        <div className="bundle-card-text">
          <div className="bundle-card-title">
            {on ? 'Module enabled' : 'Enable appointment management'}
          </div>
          <div className="bundle-card-sub">
            Your agent will handle every calendar interaction — new bookings, reschedules, cancellations, and booking modifications. Sold as one module, not à la carte.
          </div>
        </div>
        <div className="bundle-card-price">
          <span className="amount" style={{ letterSpacing: "-2px" }}>+${price}</span>
          <span className="suffix">one-time bundle</span>
        </div>
      </div>

      {on &&
      <div className="bundle-card-integration-row">
          <div className="bundle-card-integration-label">
            <Icons.Bolt size={12} />
            Calendar that powers this module
          </div>
          <IntegrationChip
          category="calendar"
          currentId={selectedIntegrations?.calendar}
          contextLabel="Appointment management module"
          openPicker={openPicker}
          style={chipStyle} />
        
        </div>
      }

      <div className="bundle-card-divider"></div>
      <div className="bundle-card-incl-head">
        <span>What's included — all enabled together</span>
        <span className="bundle-card-incl-count">{items.length} scenarios</span>
      </div>
      <div className="bundle-incl-grid">
        {items.map((s) =>
        <div className={`bundle-incl-item ${on ? 'on' : ''}`} key={s.id}>
            <div className="bundle-incl-check">
              <Icons.Check size={11} strokeWidth={3} />
            </div>
            <div className="bundle-incl-body">
              <div className="bundle-incl-name">{s.name}</div>
              <div className="bundle-incl-desc">{s.desc}</div>
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ---------- Custom scenario composer (free-form text) ----------
function CustomScenarioComposer({ onAdd, pricing, count }) {
  const [text, setText] = useStateCL('');
  const minChars = 20;
  const maxChars = 600;
  const trimmed = text.trim();
  const ready = trimmed.length >= minChars && trimmed.length <= maxChars;

  function submit() {
    if (!ready) return;
    onAdd(trimmed);
    setText('');
  }

  return (
    <div className="custom-composer">
      <div className="custom-composer-head">
        <div className="custom-composer-title">
          <span className="custom-composer-icon"><Icons.Sparkle size={13} /></span>
          {count === 0 ? 'Describe a custom scenario' : 'Add another custom scenario'}
        </div>
        <div className="custom-composer-price">
          <span className="amount">+${pricing}</span>
          <span className="suffix">one-time each</span>
        </div>
      </div>
      <textarea
        className="custom-composer-input"
        value={text}
        onChange={(e) => setText(e.target.value.slice(0, maxChars))}
        placeholder={'When a regular client calls to ask if their stylist Marcy is in this week, the agent should look at our staff schedule and tell them which days Marcy is working — without exposing the whole schedule.'}
        rows={4} />
      
      <div className="custom-composer-foot">
        <div className="custom-composer-meta">
          <Icons.Alert size={13} />
          <span>
            <b>Subject to acceptance by our AI engineers.</b> The ${pricing} will appear on your order — we charge it only after engineering confirms the scenario is implementable. If it isn't, we drop the line.
          </span>
        </div>
        <button
          className={`btn ${ready ? 'btn-primary' : 'btn-ghost'} btn-sm`}
          onClick={submit}
          disabled={!ready}
          style={!ready ? { opacity: 0.55, cursor: 'not-allowed' } : {}}>
          
          <Icons.Sparkle size={12} />
          Add to order
        </button>
      </div>
      <div className="custom-composer-chars">
        <span>
          {trimmed.length === 0 ?
          `Minimum ${minChars} characters · plain English is fine` :
          ready ?
          `Looks good — describe one scenario at a time` :
          trimmed.length < minChars ?
          `${minChars - trimmed.length} more characters needed` :
          `Trim to ${maxChars} characters or fewer`}
        </span>
        <span style={{ marginLeft: 'auto', opacity: trimmed.length === 0 ? 0.5 : 1 }}>
          {text.length}<span style={{ color: 'var(--ink-3)' }}> / {maxChars}</span>
        </span>
      </div>
    </div>);

}

function CustomScenarioRow({ scenario, onRemove }) {
  return (
    <div className="row custom-row on">
      <div className="check on custom">
        <Icons.Sparkle size={11} />
      </div>
      <div className="row-body">
        <div className="row-title">
          <span className="custom-row-name">{firstLine(scenario.text)}</span>
          <span className="pending-badge">
            <span className="pending-dot"></span>
            Pending engineer review
          </span>
        </div>
        <div className="row-desc custom-desc">{scenario.text}</div>
      </div>
      <div className="row-price">
        +$200<span className="row-price-suffix"> one-time</span>
      </div>
      <button className="row-edit" onClick={onRemove} title="Remove custom scenario">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
        </svg>
      </button>
    </div>);

}

function firstLine(text) {
  const t = text.trim();
  const m = t.match(/^[^.!?\n]{1,70}/);
  let head = m ? m[0] : t.slice(0, 70);
  if (head.length < t.length) head = head + '…';
  return head.charAt(0).toUpperCase() + head.slice(1);
}

window.ChecklistVariant = ChecklistVariant;