// T2 Falcon Admin — Add Client Flow (5-step creative stepper)

const { useState: useStateAC, useRef: useRefAC, useEffect: useEffectAC, useMemo: useMemoAC } = React;

// ===== Steps =====
const AC_STEPS = [
{ id: 'info', label: 'Client Information', icon: (p) => <I {...p}><rect x="3" y="3" width="18" height="18" rx="3" /><path d="M3 9h18M9 21V9" /></I> },
{ id: 'settings', label: 'Settings', icon: (p) => <I {...p}><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06A2 2 0 1 1 4.27 16.96l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06A2 2 0 1 1 7.04 4.27l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" /></I> },
{ id: 'channels', label: 'CommChannels', icon: (p) => <I {...p}><path d="M21 12a9 9 0 1 1-3.5-7.1l2.5-2.5v5.5h-5.5l2-2A6 6 0 1 0 18 12" /></I> },
{ id: 'apps', label: 'Applications', icon: (p) => <I {...p}><rect x="3" y="3" width="7" height="7" rx="1.5" /><rect x="14" y="3" width="7" height="7" rx="1.5" /><rect x="3" y="14" width="7" height="7" rx="1.5" /><rect x="14" y="14" width="7" height="7" rx="1.5" /></I> },
{ id: 'owner', label: 'Account Owner', icon: (p) => <I {...p}><circle cx="12" cy="8" r="4" /><path d="M4 21c0-4 4-6 8-6s8 2 8 6" /></I> }];


// Saudi Riyal symbol (small SVG glyph used in price inputs)
// Saudi Riyal — official 2025 glyph (proxied to global IcRiyal)
const RiyalGlyph = ({ size = 13 }) => <IcRiyal size={size} />;


// ===== Stepper =====
const ACStepBar = ({ current, onJump }) => {
  const pct = current / (AC_STEPS.length - 1) * 100;
  return (
    <div className="ac-stepper">
      <div className="ac-stepper-track">
        <div className="ac-stepper-fill" style={{ width: `${pct}%` }} />
        {AC_STEPS.map((s, i) => {
          const Icon = s.icon;
          const state = i < current ? 'done' : i === current ? 'active' : 'idle';
          return (
            <button
              key={s.id}
              className={`ac-stepper-dot ${state}`}
              style={{ left: `${i / (AC_STEPS.length - 1) * 100}%` }}
              onClick={() => onJump && i <= current && onJump(i)}
              type="button"
              aria-label={s.label}>
              {state === 'done' ?
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg> :
              state === 'active' ?
              <span className="ac-stepper-dot-pulse" /> :
              null}
            </button>);

        })}
      </div>
      <div className="ac-stepper-labels">
        {AC_STEPS.map((s, i) =>
        <span
          key={s.id}
          className={`ac-step-label ${i === current ? 'active' : ''} ${i < current ? 'done' : ''}`}
          style={{ left: `${i / (AC_STEPS.length - 1) * 100}%` }}>
            {s.label}
          </span>
        )}
      </div>
    </div>);

};

// ===== Profile Picture Block (matches Add User uploader) =====
const ACProfilePicture = ({ photo, onChange, label = 'Profile Picture', subLabel = 'PNG, JPG up to 2MB' }) => {
  const ref = useRefAC(null);
  const [drag, setDrag] = useStateAC(false);
  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => onChange(reader.result);
    reader.readAsDataURL(file);
  };
  return (
    <div
      className={`ac-photo-block ${drag ? 'drag-over' : ''}`}
      onDragOver={(e) => {e.preventDefault();setDrag(true);}}
      onDragLeave={() => setDrag(false)}
      onDrop={(e) => {e.preventDefault();setDrag(false);handleFile(e.dataTransfer.files[0]);}}>
      
      <div className="ac-photo-left">
        <div className="ac-avatar-circle">
          {photo ?
          <img src={photo} alt="" /> :

          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#0d3f44" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="8" r="4" /><path d="M4 20c0-4 4-6 8-6s8 2 8 6" />
            </svg>
          }
          {photo && <>
            <button
              type="button"
              className="ac-avatar-edit"
              aria-label="Edit photo"
              onClick={(e) => {e.stopPropagation();ref.current?.click();}}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 20h9" /><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
              </svg>
            </button>
            <button
              type="button"
              className="ac-avatar-delete"
              aria-label="Remove photo"
              onClick={(e) => {e.stopPropagation();onChange('');}}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="6" y1="6" x2="18" y2="18" /><line x1="6" y1="18" x2="18" y2="6" />
              </svg>
            </button>
          </>}
        </div>
        <div className="ac-photo-label">
          {label}
          <span className="sub">{subLabel}</span>
        </div>
      </div>

      <div className="ac-photo-right">
        <span className="ac-drop-hint">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 16 12 12 8 16" /><line x1="12" y1="12" x2="12" y2="21" /><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" /></svg>
          Drag a photo here or
        </span>
        <button className="btn btn-primary ac-upload-btn" type="button" onClick={() => ref.current?.click()}>Upload Photo</button>
        <input ref={ref} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => handleFile(e.target.files[0])} />
      </div>
    </div>);

};

// ===== Step 1: Client Information =====
const ACStep1 = ({ data, onChange, errors }) =>
<div className="ac-step-pane">
    <ACProfilePicture photo={data.photo} onChange={(v) => onChange('photo', v)} label="Client Picture" />

    {/* Account block */}
    <div className="ac-field-grid ac-grid-4" style={{ marginTop: 24 }}>
      <div className="ac-field">
        <label className="ac-label">Account Name <span className="req">*</span></label>
        <input
        className={`ac-input ${errors.accountName ? 'error' : ''}`}
        placeholder="Start with letter · Max 30 Characters"
        value={data.accountName}
        onChange={(e) => onChange('accountName', e.target.value)} />
      
        {errors.accountName && <span className="ac-error-msg">*Please fill this field</span>}
      </div>
      <div className="ac-field">
        <label className="ac-label">Finance ID <span className="req">*</span></label>
        <input className="ac-input" value={data.financeId} onChange={(e) => onChange('financeId', e.target.value)} />
      </div>
      <div className="ac-field">
        <label className="ac-label">Classification Category</label>
        <div className="ac-select-wrap">
          <select className="ac-input" value={data.classCat} onChange={(e) => onChange('classCat', e.target.value)}>
            <option value=""></option>
            <option>Government</option>
            <option>Banking</option>
            <option>Healthcare</option>
            <option>Energy</option>
            <option>Retail</option>
          </select>
          <span className="ac-select-chev"><IcChevronDown size={14} stroke={2} /></span>
        </div>
      </div>
      <div className="ac-field">
        <label className="ac-label">Classification Sub Category</label>
        <div className="ac-select-wrap">
          <select className="ac-input" value={data.classSub} onChange={(e) => onChange('classSub', e.target.value)}>
            <option value=""></option>
            <option>Public Sector</option>
            <option>Commercial</option>
            <option>Non-profit</option>
          </select>
          <span className="ac-select-chev"><IcChevronDown size={14} stroke={2} /></span>
        </div>
      </div>
    </div>

    {/* Account Official — section divider, not a nested card */}
    <div className="ac-section-block">
      <div className="ac-section-head">
        <span className="ac-section-title">Account Official</span>
      </div>
      <div className="ac-field-grid ac-grid-4">
        <div className="ac-field">
          <label className="ac-label">Entity Name</label>
          <input className="ac-input" value={data.entityName} onChange={(e) => onChange('entityName', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Authority Letter Type</label>
          <div className="ac-select-wrap">
            <select className="ac-input" value={data.authority} onChange={(e) => onChange('authority', e.target.value)}>
              <option>Government</option>
              <option>Private</option>
              <option>Joint Venture</option>
            </select>
            <span className="ac-select-chev"><IcChevronDown size={14} stroke={2} /></span>
          </div>
        </div>
        <div className="ac-field">
          <label className="ac-label">Sector</label>
          <input className="ac-input" value={data.sector} onChange={(e) => onChange('sector', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Budget No.</label>
          <input className="ac-input" value={data.budgetNo} onChange={(e) => onChange('budgetNo', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Country</label>
          <div className="ac-select-wrap">
            <select className="ac-input" value={data.country} onChange={(e) => onChange('country', e.target.value)}>
              <option value=""></option>
              <option>Saudi Arabia</option>
              <option>United Arab Emirates</option>
              <option>Egypt</option>
              <option>Jordan</option>
            </select>
            <span className="ac-select-chev"><IcChevronDown size={14} stroke={2} /></span>
          </div>
        </div>
        <div className="ac-field">
          <label className="ac-label">City</label>
          <div className="ac-select-wrap">
            <select className="ac-input" value={data.city} onChange={(e) => onChange('city', e.target.value)}>
              <option value=""></option>
              <option>Riyadh</option>
              <option>Jeddah</option>
              <option>Dammam</option>
              <option>Mecca</option>
            </select>
            <span className="ac-select-chev"><IcChevronDown size={14} stroke={2} /></span>
          </div>
        </div>
        <div className="ac-field">
          <label className="ac-label">District</label>
          <input className="ac-input" value={data.district} onChange={(e) => onChange('district', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Street</label>
          <input className="ac-input" value={data.street} onChange={(e) => onChange('street', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Building Number</label>
          <input className="ac-input" value={data.bldg} onChange={(e) => onChange('bldg', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Postal Code</label>
          <input className="ac-input" value={data.postal} onChange={(e) => onChange('postal', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Additional Address</label>
          <input className="ac-input" value={data.addressExtra} onChange={(e) => onChange('addressExtra', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Another ID</label>
          <input className="ac-input" value={data.anotherId} onChange={(e) => onChange('anotherId', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">VAT Registration Number</label>
          <input className="ac-input" value={data.vat} onChange={(e) => onChange('vat', e.target.value)} />
        </div>
      </div>
    </div>
  </div>;


// ===== Step 2: Settings =====
const ACStep2 = ({ data, onChange }) => {
  const [pendingIp, setPendingIp] = useStateAC('');
  const removeIp = (ip) => onChange('allowedIps', data.allowedIps.filter((x) => x !== ip));
  const addIp = (val) => {
    const v = (val || pendingIp).trim();
    if (!v) return;
    if (data.allowedIps.includes(v)) {setPendingIp('');return;}
    onChange('allowedIps', [...data.allowedIps, v]);
    setPendingIp('');
  };

  return (
    <div className="ac-step-pane">
      <div className="ac-settings-grid">
        {/* LEFT — security + ips */}
        <div className="ac-settings-left">
          <div className="ac-block-title">Password Security Level</div>
          <div className="ac-radio-cards">
            <label className={`ac-radio-card ${data.security === 'normal' ? 'selected' : ''}`}>
              <input type="radio" name="sec" checked={data.security === 'normal'} onChange={() => onChange('security', 'normal')} />
              <span className="ac-radio-mark"></span>
              <div className="ac-radio-text">
                <strong>Normal</strong>
                <em>Username, Password, OTP</em>
              </div>
            </label>
            <label className={`ac-radio-card ${data.security === 'advanced' ? 'selected' : ''}`}>
              <input type="radio" name="sec" checked={data.security === 'advanced'} onChange={() => onChange('security', 'advanced')} />
              <span className="ac-radio-mark"></span>
              <div className="ac-radio-text">
                <strong>Advanced</strong>
                <em>Comply with NCA regulations, <a href="#" onClick={(e) => e.preventDefault()}>press here for more details.</a></em>
              </div>
            </label>
          </div>

          <div className="ac-block-title">Allowed IPs</div>
          <div className="ac-ip-row">
            <button className="ac-ip-add" type="button" onClick={() => {
              const el = document.getElementById('ac-ip-input');
              el?.focus();
            }}>
              IP Address
            </button>
            {data.allowedIps.map((ip) =>
            <span key={ip} className="ac-ip-chip">
                <span>{ip}</span>
                <button type="button" onClick={() => removeIp(ip)} aria-label="Remove"><IcClose size={10} stroke={2.4} /></button>
              </span>
            )}
          </div>
          <input
            id="ac-ip-input"
            className="ac-input ac-ip-input"
            placeholder="Enter IP Address (IPv4 or IPv6) and press Enter"
            value={pendingIp}
            onChange={(e) => setPendingIp(e.target.value)}
            onKeyDown={(e) => {if (e.key === 'Enter') {e.preventDefault();addIp();}}} />
          
          <div className="ac-hint-text">* Restrict platform access and limit it from these IPs only</div>
        </div>

        {/* RIGHT — limitations */}
        <aside className="ac-settings-right">
          <div className="ac-side-head">
            <span className="ac-side-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /><circle cx="12" cy="16" r="1.2" fill="currentColor" /></svg>
            </span>
            <span>Account Limitations</span>
          </div>

          <div className="limit-row">
            <div className="limit-row-title">Max normal user limit</div>
            <div className="limit-row-cols">
              <div className="limit-col">
                <span className="limit-col-label">Current existing</span>
                <input className="ac-input limit-current" value={data.currentNormal ?? 0} disabled readOnly />
              </div>
              <div className="limit-col">
                <span className="limit-col-label">Max allowed</span>
                <NumberStepper value={data.maxNormal} onChange={(v) => onChange('maxNormal', v)} />
              </div>
            </div>
          </div>

          <div className="limit-row">
            <div className="limit-row-title">Max System User Limit</div>
            <div className="limit-row-cols">
              <div className="limit-col">
                <span className="limit-col-label">Current existing</span>
                <input className="ac-input limit-current" value={data.currentSystem ?? 0} disabled readOnly />
              </div>
              <div className="limit-col">
                <span className="limit-col-label">Max allowed</span>
                <NumberStepper value={data.maxSystem} onChange={(v) => onChange('maxSystem', v)} />
              </div>
            </div>
          </div>

          <div className="limit-row">
            <div className="limit-row-title">Max Node Level</div>
            <div className="limit-row-cols">
              <div className="limit-col">
                <span className="limit-col-label">Current existing</span>
                <input className="ac-input limit-current" value={data.currentNode ?? 0} disabled readOnly />
              </div>
              <div className="limit-col">
                <span className="limit-col-label">Max allowed</span>
                <NumberStepper value={data.maxNode} onChange={(v) => onChange('maxNode', v)} />
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>);

};

const NumberStepper = ({ value, onChange, min = 0, max = 9999 }) => {
  const set = (v) => onChange(Math.max(min, Math.min(max, v)));
  return (
    <div className="ac-number">
      <input
        type="number"
        className="ac-input"
        value={value}
        onChange={(e) => set(Number(e.target.value) || 0)} />
      
      <div className="ac-number-arrows">
        <button type="button" onClick={() => set(value + 1)} aria-label="Increase"><svg width="9" height="6" viewBox="0 0 12 8" fill="none"><path d="M1 7l5-5 5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
        <button type="button" onClick={() => set(value - 1)} aria-label="Decrease"><svg width="9" height="6" viewBox="0 0 12 8" fill="none"><path d="M1 1l5 5 5-5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
      </div>
    </div>);

};

// ===== Step 3 + 4 share the same row table =====
const ACServiceTable = ({ rows, onChange, t }) => {
  const updateRow = (id, patch) => onChange(rows.map((r) => r.id === id ? { ...r, ...patch } : r));
  const [page, setPage] = useStateAC(1);
  const [pageSize, setPageSize] = useStateAC(10);
  const total = rows.length;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  const safePage = Math.min(page, totalPages);
  const startIdx = (safePage - 1) * pageSize;
  const visibleRows = rows.slice(startIdx, startIdx + pageSize);
  return (
    <div className="ac-svc-table">
      <div className="ac-svc-head">
        <div className="ac-svc-cell ac-c-vis">Visibility</div>
        <div className="ac-svc-cell ac-c-name">Name</div>
        <div className="ac-svc-cell ac-c-type">Price Type</div>
        <div className="ac-svc-cell ac-c-val">Price Value</div>
        <div className="ac-svc-cell ac-c-status">Status</div>
      </div>
      {visibleRows.map((r) =>
      <div key={r.id} className={`ac-svc-row ${!r.visible ? 'dim' : ''}`}>
          <div className="ac-svc-cell ac-c-vis">
            <button
            type="button"
            role="switch"
            aria-checked={r.visible}
            className={`vis-toggle ${r.visible ? 'on' : ''}`}
            onClick={() => updateRow(r.id, { visible: !r.visible })}>
            
              <span className="vis-toggle-dot" />
            </button>
          </div>
          <div className="ac-svc-cell ac-c-name"><strong>{r.name}</strong></div>
          <div className="ac-svc-cell ac-c-type">
            <div className="ac-select-wrap small">
              <select
              className="ac-input small"
              value={r.priceType || ''}
              disabled={!r.visible}
              onChange={(e) => updateRow(r.id, { priceType: e.target.value })}>
              
                <option value="">---</option>
                <option value="OneTime">One Time</option>
                <option value="Monthly">Monthly</option>
                <option value="Yearly">Yearly</option>
                <option value="Quarterly">Quarterly</option>
              </select>
              <span className="ac-select-chev"><IcChevronDown size={12} stroke={2} /></span>
            </div>
          </div>
          <div className="ac-svc-cell ac-c-val">
            <div className="ac-price-input">
              <span className="ac-price-icon"><RiyalGlyph size={11} /></span>
              <input
              className="ac-input small"
              type="number"
              value={r.priceValue ?? ''}
              disabled={!r.visible}
              placeholder={!r.visible ? '----' : '0'}
              onChange={(e) => updateRow(r.id, { priceValue: Number(e.target.value) || 0 })} />
            
            </div>
          </div>
          <div className="ac-svc-cell ac-c-status">
            {!r.visible ?
          <span className="ac-status-dash">------</span> :

          <span className="ac-status-pill" style={{ fontSize: "12px", fontWeight: "600" }}>Inactive</span>
          }
          </div>
        </div>
      )}
      {window.TablePagination &&
      <window.TablePagination
        total={total}
        page={safePage}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={(n) => {setPageSize(n);setPage(1);}}
        t={t || {}} />
      }
    </div>);

};

// Step 3: CommChannels
const ACStep3 = ({ data, onChange, t }) =>
<div className="ac-step-pane">
    <ACServiceTable rows={data.channels} onChange={(rows) => onChange('channels', rows)} t={t} />
  </div>;


// Step 4: Applications
const ACStep4 = ({ data, onChange, t }) =>
<div className="ac-step-pane">
    <ACServiceTable rows={data.apps} onChange={(rows) => onChange('apps', rows)} t={t} />
  </div>;


// Step 5: Account Owner
const ACStep5 = ({ data, onChange }) => {
  return (
    <div className="ac-step-pane">
      <ACProfilePicture photo={data.ownerPhoto} onChange={(v) => onChange('ownerPhoto', v)} label="Owner Picture" />

      <div className="ac-field-grid ac-grid-4" style={{ marginTop: 24 }}>
        <div className="ac-field">
          <label className="ac-label">First Name <span className="req">*</span></label>
          <input className="ac-input" value={data.ownerFirst} onChange={(e) => onChange('ownerFirst', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Last Name <span className="req">*</span></label>
          <input className="ac-input" value={data.ownerLast} onChange={(e) => onChange('ownerLast', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">User Name <span className="req">*</span></label>
          <input className="ac-input" value={data.ownerUser} onChange={(e) => onChange('ownerUser', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Password</label>
          <div className="ac-pwd-wrap">
            <input
              className="ac-input"
              type="text"
              value={data.ownerPwd}
              disabled
              readOnly />
          </div>
        </div>
        <div className="ac-field">
          <label className="ac-label">National ID / Iqama</label>
          <input className="ac-input" value={data.ownerNid} onChange={(e) => onChange('ownerNid', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Phone Number <span className="req">*</span></label>
          <input className="ac-input" value={data.ownerPhone} onChange={(e) => onChange('ownerPhone', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Email Address <span className="req">*</span></label>
          <input className="ac-input" value={data.ownerEmail} onChange={(e) => onChange('ownerEmail', e.target.value)} />
        </div>
        <div className="ac-field">
          <label className="ac-label">Role</label>
          <div className="ac-pwd-wrap">
            <input
              className="ac-input"
              type="text"
              value={data.ownerRole}
              disabled
              readOnly />
          </div>
        </div>
      </div>
    </div>);

};

// ===== Main Flow =====
const AddClientFlow = ({ onClose, t, pushToast, parentNode }) => {
  const [step, setStep] = useStateAC(0);
  const [direction, setDirection] = useStateAC(1);
  const [errors, setErrors] = useStateAC({});
  const [sendingOpen, setSendingOpen] = useStateAC(false);
  const [successOpen, setSuccessOpen] = useStateAC(false);
  const [delivery, setDelivery] = useStateAC('email');
  const [form, setForm] = useStateAC({
    photo: '',
    accountName: '', financeId: '', classCat: '', classSub: '',
    entityName: '', authority: 'Government', sector: '', budgetNo: '',
    country: '', city: '', district: '', street: '', bldg: '', postal: '', addressExtra: '', anotherId: '', vat: '',
    security: 'normal',
    allowedIps: ['192.168.0.1', '192.168.0.1'],
    maxNormal: 20, maxSystem: 5, maxNode: 2,
    currentNormal: 0, currentSystem: 5, currentNode: 0,
    channels: [
    { id: 'ch1', name: 'WhatsApp', visible: true, priceType: 'Monthly', priceValue: 2000 },
    { id: 'ch2', name: 'Voice', visible: false, priceType: '', priceValue: null },
    { id: 'ch3', name: 'AI', visible: true, priceType: 'OneTime', priceValue: 2000 }],

    apps: [
    { id: 'ap1', name: 'Basic Send App', visible: true, priceType: 'Monthly', priceValue: 2000 },
    { id: 'ap2', name: 'Survey Engine', visible: false, priceType: '', priceValue: null },
    { id: 'ap3', name: 'Campaign Engine', visible: true, priceType: 'OneTime', priceValue: 2000 }],

    ownerPhoto: '', ownerFirst: '', ownerLast: '', ownerUser: '',
    ownerPwd: '#123455', ownerNid: '', ownerPhone: '', ownerEmail: '', ownerRole: 'Account Owner'
  });

  const update = (key, value) => {
    setForm((f) => ({ ...f, [key]: value }));
    if (errors[key]) setErrors((e) => ({ ...e, [key]: undefined }));
  };

  const validateStep1 = () => {
    const errs = {};
    if (!form.accountName.trim()) errs.accountName = true;
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const isLast = step === AC_STEPS.length - 1;
  const handleNext = () => {
    if (step === 0 && !validateStep1()) {return;}
    if (isLast) {
      setSendingOpen(true);
      return;
    }
    setDirection(1);
    setStep((s) => s + 1);
  };
  const handlePrev = () => {
    if (step === 0) return;
    setDirection(-1);
    setStep((s) => s - 1);
  };

  return (
    <div className="ac-page">
      {/* Top bar */}
      <div className="ac-topbar">
        <div className="ac-topbar-brand">
          <span className="ac-brand-mark"><T2Mark size={26} color="#0d3f44" /></span>
          <span className="ac-brand-name">Falcon</span>
        </div>
        <div className="ac-topbar-actions">
          <button className="btn btn-secondary" type="button" onClick={onClose}>Cancel</button>
          {step > 0 &&
          <button className="btn btn-secondary" type="button" onClick={handlePrev}>Previous</button>
          }
          <button className="btn btn-primary" type="button" onClick={handleNext}>{isLast ? 'Save' : 'Next'}</button>
        </div>
      </div>

      {/* Body */}
      <div className="ac-body">
        <div className="ac-card">
          <div className="ac-card-head">
            <div className="ac-card-title">Create New Client</div>
            <div className="ac-step-counter">step <strong>{step + 1}/{AC_STEPS.length}</strong></div>
          </div>

          <ACStepBar current={step} onJump={(i) => {setDirection(i > step ? 1 : -1);setStep(i);}} />

          <div className="ac-card-body" style={{ height: "751px" }}>
            <div key={step} className={`ac-anim-pane ${direction > 0 ? 'in-right' : 'in-left'}`}>
              {step === 0 && <ACStep1 data={form} onChange={update} errors={errors} />}
              {step === 1 && <ACStep2 data={form} onChange={update} />}
              {step === 2 && <ACStep3 data={form} onChange={update} t={t} />}
              {step === 3 && <ACStep4 data={form} onChange={update} t={t} />}
              {step === 4 && <ACStep5 data={form} onChange={update} />}
            </div>
          </div>
        </div>
      </div>

      {sendingOpen &&
      <SendCredentialsModal
        delivery={delivery}
        setDelivery={setDelivery}
        owner={{
          first: form.ownerFirst || 'Jawad',
          last: form.ownerLast || 'Lababneh',
          phone: form.ownerPhone || '966567415590',
          email: form.ownerEmail || 'j.lababneh@t2.sa'
        }}
        onCancel={() => setSendingOpen(false)}
        onSend={() => {setSendingOpen(false);setSuccessOpen(true);}} />
      }

      {successOpen &&
      <SuccessModal
        onClose={() => {
          setSuccessOpen(false);
          pushToast(t.toastNodeAdded || 'Client created ✓');
          onClose();
        }} />
      }
    </div>);

};

// ===== Send Credentials Modal =====
const SendCredentialsModal = ({ delivery, setDelivery, owner, onCancel, onSend }) => {
  const options = [
  { id: 'email', label: 'Send via Email', src: 'admin/assets/send-email.svg' },
  { id: 'sms', label: 'Send via SMS', src: 'admin/assets/send-sms.svg' },
  { id: 'both', label: 'Both, SMS and Email', src: 'admin/assets/send-both.svg' }];

  return (
    <div className="ac-modal-overlay" onClick={onCancel}>
      <div className="ac-modal ac-send-modal" onClick={(e) => e.stopPropagation()}>
        <button className="ac-modal-close" type="button" onClick={onCancel} aria-label="Close">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6L18 18M18 6L6 18" /></svg>
        </button>
        <div className="ac-modal-head">
          <h3 className="ac-modal-title">Sending Credentials</h3>
          <p className="ac-modal-sub">An email and/or SMS with the username and password will be sent to the account owner</p>
        </div>
        <div className="ac-send-section">
          <div className="ac-send-label">Delivery method:</div>
          <div className="ac-send-options">
            {options.map((o) =>
            <button key={o.id} type="button" className={`ac-send-card ${delivery === o.id ? 'is-selected' : ''}`} onClick={() => setDelivery(o.id)}>
              <div className="ac-send-radio">
                <span className="ac-send-radio-outer">
                  {delivery === o.id && <span className="ac-send-radio-inner" />}
                </span>
                <span className="ac-send-card-label">{o.label}</span>
              </div>
              <div className="ac-send-illo"><img src={o.src} alt="" draggable="false" /></div>
            </button>
            )}
          </div>
        </div>
        <div className="ac-send-summary">
          <div className="ac-send-summary-item">
            <span className="ac-send-summary-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="3.5" /><path d="M5 20a7 7 0 0 1 14 0" strokeLinecap="round" /></svg>
            </span>
            <div>
              <div className="ac-send-summary-key">Account owner</div>
              <div className="ac-send-summary-val">{owner.first} {owner.last}</div>
            </div>
          </div>
          <div className="ac-send-summary-item">
            <span className="ac-send-summary-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="6" y="3" width="12" height="18" rx="2" /><circle cx="12" cy="18" r="0.8" fill="currentColor" /></svg>
            </span>
            <div>
              <div className="ac-send-summary-key">Phone Number</div>
              <div className="ac-send-summary-val">{owner.phone}</div>
            </div>
          </div>
          <div className="ac-send-summary-item">
            <span className="ac-send-summary-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="6" width="18" height="13" rx="2" /><path d="M3 8l9 6 9-6" /></svg>
            </span>
            <div>
              <div className="ac-send-summary-key">Email</div>
              <div className="ac-send-summary-val">{owner.email}</div>
            </div>
          </div>
        </div>
        <div className="ac-modal-actions">
          <button className="btn btn-link" type="button" onClick={onCancel}>Cancel</button>
          <button className="btn btn-primary" type="button" onClick={onSend}>Send Credentials</button>
        </div>
      </div>
    </div>);

};

// ===== Success Modal =====
const SuccessModal = ({ onClose }) => {
  return (
    <div className="ac-modal-overlay" onClick={onClose}>
      <div className="ac-modal ac-success-modal" onClick={(e) => e.stopPropagation()}>
        <button className="ac-modal-close" type="button" onClick={onClose} aria-label="Close">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6L18 18M18 6L6 18" /></svg>
        </button>
        <div className="ac-success-illo"><img src="admin/assets/successfully.svg" alt="" draggable="false" /></div>
        <div className="ac-success-text">
          <h3 className="ac-success-title">Completed successfully</h3>
          <p className="ac-success-sub">Credentials sent to the user</p>
        </div>
      </div>
    </div>);

};

// ===== Illustrations =====
const SendEmailIllo = () =>
<svg viewBox="0 0 160 110" width="100%" height="100%" aria-hidden>
    <circle cx="80" cy="58" r="44" fill="#E1ECEA" />
    <path d="M40 48 L80 76 L120 48 Z" fill="#0d3f44" />
    <path d="M40 48 L120 48 L120 86 L40 86 Z" fill="#fff" stroke="#0d3f44" strokeWidth="2" />
    <path d="M40 48 L80 76 L120 48" fill="none" stroke="#0d3f44" strokeWidth="2" />
    <path d="M70 52 c-3 -3 -3 -8 0 -11 l5 -5 c3 -3 8 -3 11 0 c3 3 3 8 0 11 l-2 2" stroke="#0d3f44" strokeWidth="2.5" fill="none" strokeLinecap="round" />
    <path d="M90 60 c3 3 3 8 0 11 l-5 5 c-3 3 -8 3 -11 0 c-3 -3 -3 -8 0 -11 l2 -2" stroke="#0d3f44" strokeWidth="2.5" fill="none" strokeLinecap="round" />
  </svg>;

const SendSmsIllo = () =>
<svg viewBox="0 0 160 110" width="100%" height="100%" aria-hidden>
    <circle cx="80" cy="58" r="44" fill="#E1ECEA" />
    <rect x="46" y="36" width="56" height="44" rx="6" fill="#0d3f44" />
    <rect x="68" y="40" width="12" height="2" rx="1" fill="#E1ECEA" />
    <circle cx="62" cy="58" r="2.5" fill="#fff" />
    <circle cx="72" cy="58" r="2.5" fill="#fff" />
    <circle cx="82" cy="58" r="2.5" fill="#fff" />
    <circle cx="92" cy="58" r="2.5" fill="#fff" />
    <circle cx="108" cy="64" r="14" fill="#0d3f44" />
    <path d="M102 64 v-4 c0 -3 3 -6 6 -6 c3 0 6 3 6 6 v4" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" />
    <rect x="100" y="64" width="16" height="12" rx="2" fill="#fff" />
    <circle cx="108" cy="70" r="1.5" fill="#0d3f44" />
  </svg>;

const SendBothIllo = () =>
<svg viewBox="0 0 160 110" width="100%" height="100%" aria-hidden>
    <circle cx="80" cy="58" r="44" fill="#E1ECEA" />
    <path d="M30 80 L130 38 L100 70 L78 64 Z" fill="#0d3f44" />
    <path d="M78 64 L100 70 L84 88 Z" fill="#1a5e63" />
    <circle cx="56" cy="42" r="9" fill="#fff" stroke="#0d3f44" strokeWidth="1.6" />
    <text x="56" y="46" textAnchor="middle" fontSize="9" fill="#0d3f44" fontFamily="sans-serif" fontWeight="700">@</text>
    <circle cx="106" cy="78" r="9" fill="#fff" stroke="#0d3f44" strokeWidth="1.6" />
    <text x="106" y="81" textAnchor="middle" fontSize="6" fill="#0d3f44" fontFamily="sans-serif" fontWeight="700">SMS</text>
    <circle cx="40" cy="64" r="2" fill="#0d3f44" />
    <circle cx="50" cy="78" r="1.5" fill="#0d3f44" />
    <circle cx="124" cy="56" r="1.5" fill="#0d3f44" />
  </svg>;

const SuccessIllo = () =>
<svg viewBox="0 0 220 200" width="100%" height="100%" aria-hidden>
    <circle cx="110" cy="110" r="64" fill="#E1ECEA" />
    {/* sparkles & circles */}
    <path d="M48 60 l3 7 l7 3 l-7 3 l-3 7 l-3 -7 l-7 -3 l7 -3 z" fill="none" stroke="#1a5e63" strokeWidth="1.6" strokeLinejoin="round" />
    <path d="M168 152 l2.5 6 l6 2.5 l-6 2.5 l-2.5 6 l-2.5 -6 l-6 -2.5 l6 -2.5 z" fill="none" stroke="#1a5e63" strokeWidth="1.4" strokeLinejoin="round" />
    <circle cx="62" cy="140" r="3" fill="none" stroke="#0d3f44" strokeWidth="1.4" />
    <circle cx="174" cy="68" r="3" fill="none" stroke="#0d3f44" strokeWidth="1.4" />
    <circle cx="118" cy="38" r="2.5" fill="none" stroke="#0d3f44" strokeWidth="1.4" />
    <circle cx="84" cy="170" r="2" fill="none" stroke="#0d3f44" strokeWidth="1.4" />
    {/* clipboard */}
    <rect x="80" y="68" width="60" height="78" rx="6" fill="#0d3f44" />
    <rect x="92" y="60" width="36" height="14" rx="6" fill="#fff" stroke="#0d3f44" strokeWidth="2" />
    <circle cx="110" cy="67" r="4" fill="none" stroke="#0d3f44" strokeWidth="1.6" />
    <path d="M106 70 a4 4 0 0 1 8 0" fill="none" stroke="#0d3f44" strokeWidth="1.6" />
    {/* lines on clipboard */}
    <rect x="92" y="92" width="36" height="3" rx="1.5" fill="#fff" />
    <rect x="92" y="102" width="26" height="3" rx="1.5" fill="#fff" />
    {/* check pill */}
    <rect x="68" y="116" width="48" height="14" rx="7" fill="#9bb6b1" />
    <path d="M76 123 l4 4 l9 -8" stroke="#fff" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    <rect x="92" y="124" width="20" height="3" rx="1.5" fill="#fff" opacity="0.85" />
    {/* check badge */}
    <circle cx="138" cy="142" r="14" fill="#0d3f44" />
    <path d="M132 142 l4 4 l9 -8" stroke="#fff" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
  </svg>;


window.AddClientFlow = AddClientFlow;