/* global React, Icon */
// RefsPicker — multi-select picker for trigger form (3 modes: feature / suite / tc_list)

const MOCK_FEATURES = [
  { id: "f_gift",   name: "Gift System",     order_index: 1, suiteCount: 4, tcCount: 24 },
  { id: "f_wallet", name: "Wallet",          order_index: 2, suiteCount: 3, tcCount: 12 },
  { id: "f_auth",   name: "Authentication",  order_index: 3, suiteCount: 2, tcCount: 9 },
  { id: "f_search", name: "Search & Catalog",order_index: 4, suiteCount: 2, tcCount: 7 },
  { id: "f_promo",  name: "Promotions",      order_index: 5, suiteCount: 1, tcCount: 5 },
];

const MOCK_SUITES = [
  { id: "s_sell",  name: "Sell Gift",       feature_id: "f_gift",   tcCount: 8 },
  { id: "s_inv",   name: "Inventory",       feature_id: "f_gift",   tcCount: 6 },
  { id: "s_ship",  name: "Shipping",        feature_id: "f_gift",   tcCount: 5 },
  { id: "s_promo2",name: "Gift Promotions", feature_id: "f_gift",   tcCount: 5 },
  { id: "s_bal",   name: "Balance",         feature_id: "f_wallet", tcCount: 4 },
  { id: "s_top",   name: "Top-up",          feature_id: "f_wallet", tcCount: 5 },
  { id: "s_xfer",  name: "Transfer",        feature_id: "f_wallet", tcCount: 3 },
  { id: "s_login", name: "Login flow",      feature_id: "f_auth",   tcCount: 5 },
  { id: "s_session",name:"Session mgmt",    feature_id: "f_auth",   tcCount: 4 },
];

const MOCK_TCS = [
  { id: "TC-001", suite_id: "s_sell", feature_id: "f_gift",  description: "User sells single gift, balance updates",      status: "pass" },
  { id: "TC-002", suite_id: "s_sell", feature_id: "f_gift",  description: "Sell with insufficient inventory returns 409", status: "pass" },
  { id: "TC-003", suite_id: "s_sell", feature_id: "f_gift",  description: "Sell unauthenticated returns 401",              status: "fail" },
  { id: "TC-004", suite_id: "s_sell", feature_id: "f_gift",  description: "Sell with bundled discount applies coupon",     status: "pass" },
  { id: "TC-005", suite_id: "s_sell", feature_id: "f_gift",  description: "Sell idempotency key prevents double charge",   status: "pass" },
  { id: "TC-006", suite_id: "s_sell", feature_id: "f_gift",  description: "Bulk sell processes 50 gifts atomically",       status: "draft" },
  { id: "TC-018", suite_id: "s_inv",  feature_id: "f_gift",  description: "Inventory decrements after successful sale",    status: "pass" },
  { id: "TC-019", suite_id: "s_inv",  feature_id: "f_gift",  description: "Inventory blocks negative stock",               status: "pass" },
  { id: "TC-101", suite_id: "s_bal",  feature_id: "f_wallet",description: "Balance returns 0 for new user",                status: "pass" },
  { id: "TC-102", suite_id: "s_bal",  feature_id: "f_wallet",description: "Balance reflects pending transactions",         status: "fail" },
  { id: "TC-201", suite_id: "s_login",feature_id: "f_auth",  description: "Login with valid credentials returns token",    status: "pass" },
  { id: "TC-202", suite_id: "s_login",feature_id: "f_auth",  description: "Login with wrong password returns 401",         status: "pass" },
];

// ─── Pure picker component ─────────────────────────────────────────
const RefsPicker = ({ mode = "feature", selectedRefs = [], onChange, disabled, state = "default" }) => {
  const [q, setQ] = React.useState("");
  const [collapsed, setCollapsed] = React.useState({});
  const sel = new Set(selectedRefs);

  const toggle = (id) => {
    const next = new Set(sel);
    if (next.has(id)) next.delete(id); else next.add(id);
    onChange && onChange([...next]);
  };
  const removeAll = () => onChange && onChange([]);
  const remove = (id) => { const n = new Set(sel); n.delete(id); onChange && onChange([...n]); };

  // selected chips header
  const allItems = mode === "feature" ? MOCK_FEATURES : mode === "suite" ? MOCK_SUITES : MOCK_TCS;
  const selectedItems = allItems.filter(i => sel.has(i.id));

  return (
    <div className={"rp" + (disabled ? " rp--disabled" : "")}>
      {/* Mode segmented control */}
      <div className="rp__modes">
        <span className="rp__modes-label">Run scope</span>
        <div className="seg-group">
          <span className={"seg" + (mode === "feature" ? " seg--active" : "")}>Feature</span>
          <span className={"seg" + (mode === "suite" ? " seg--active" : "")}>Suite</span>
          <span className={"seg" + (mode === "tc_list" ? " seg--active" : "")}>Test cases</span>
        </div>
        <span className="rp__modes-hint muted">
          {mode === "feature" && "Trigger runs every TC inside the selected features"}
          {mode === "suite" && "Trigger runs every TC inside the selected suites"}
          {mode === "tc_list" && "Trigger runs only the picked test cases"}
        </span>
      </div>

      {/* Selected chips bar */}
      <div className="rp__selected">
        <div className="rp__selected-h">
          <span className="rp__selected-count">
            <b>{selectedItems.length}</b> {mode === "feature" ? "features" : mode === "suite" ? "suites" : "test cases"} selected
          </span>
          {selectedItems.length === allItems.length && allItems.length > 0 && (
            <span className="chip chip--accent">All selected</span>
          )}
          <div style={{flex:1}}/>
          {selectedItems.length > 0 && (
            <button className="link-btn">Clear all</button>
          )}
        </div>
        <div className="rp__chips">
          {selectedItems.length === 0 && state !== "validation" && (
            <span className="rp__chips-empty muted">Pick at least one to continue</span>
          )}
          {state === "validation" && selectedItems.length === 0 && (
            <span className="rp__chips-error"><Icon name="x" size={11}/>At least 1 {mode === "feature" ? "feature" : mode === "suite" ? "suite" : "test case"} must be selected</span>
          )}
          {selectedItems.map(it => (
            <span key={it.id} className="rp-chip">
              {mode === "tc_list" && <span className={"dot " + it.status} style={{marginRight:2}}/>}
              {mode === "tc_list" ? <span className="mono" style={{fontSize:10.5}}>{it.id}</span> : <span>{it.name}</span>}
              <button className="rp-chip__x" onClick={() => remove(it.id)} aria-label="Remove"><Icon name="x" size={10}/></button>
            </span>
          ))}
        </div>
      </div>

      {/* Search bar */}
      <div className="rp__search">
        <Icon name="search" size={12}/>
        <input
          placeholder={mode === "feature" ? "Search features…" : mode === "suite" ? "Search suites…" : "Search test cases by ID or description…"}
          value={q} onChange={(e) => setQ(e.target.value)}
        />
        {q && <button className="link-btn" onClick={() => setQ("")}>Clear</button>}
        {state === "search" && (
          <span className="muted mono" style={{fontSize:10.5}}>3 of 24 matches</span>
        )}
      </div>

      {/* List body */}
      <div className="rp__body">
        {state === "loading" && (
          <div className="rp__skel">
            {[1,2,3,4,5].map(i => <div key={i} className="rp-skel-row"><span className="rp-skel-box"/><span className="rp-skel-line" style={{width: 60 + i*30 + '%'}}/></div>)}
          </div>
        )}

        {state === "empty" && (
          <div className="rp__empty">
            <Icon name="folder" size={28} style={{color:'var(--fg-4)'}}/>
            <div className="rp__empty-t">No features yet</div>
            <div className="rp__empty-s muted">Triggers need at least one feature, suite, or TC to fire on. Create one first.</div>
            <button className="btn btn--primary"><Icon name="plus" size={11}/>Create feature</button>
          </div>
        )}

        {state === "no-match" && (
          <div className="rp__empty">
            <Icon name="search" size={24} style={{color:'var(--fg-4)'}}/>
            <div className="rp__empty-t">No matches for "{q || 'foo'}"</div>
            <div className="rp__empty-s muted">Try a shorter query or a TC id like <span className="mono inline-code">TC-018</span>.</div>
            <button className="btn">Clear search</button>
          </div>
        )}

        {state === "error" && (
          <div className="rp__empty rp__empty--error">
            <Icon name="x" size={24} style={{color:'var(--fail)'}}/>
            <div className="rp__empty-t">Could not load features</div>
            <div className="rp__empty-s muted">Network error · staging API returned 503. <span className="mono inline-code">req_id: 4f12a8</span></div>
            <button className="btn"><Icon name="refresh" size={11}/>Retry</button>
          </div>
        )}

        {(state === "default" || state === "search" || state === "validation") && (
          <>
            {/* Mode: feature → flat list */}
            {mode === "feature" && (
              <div className="rp-list">
                <div className="rp-list__bar">
                  <label className="rp-row__check">
                    <input type="checkbox" checked={selectedItems.length === MOCK_FEATURES.length} readOnly/>
                  </label>
                  <span className="muted">Select all visible</span>
                  <div style={{flex:1}}/>
                  <span className="muted mono" style={{fontSize:10.5}}>{MOCK_FEATURES.length} features</span>
                </div>
                {MOCK_FEATURES.map(f => (
                  <label key={f.id} className={"rp-row" + (sel.has(f.id) ? " rp-row--on" : "")} onClick={(e) => { e.preventDefault(); toggle(f.id); }}>
                    <span className="rp-row__check">
                      <input type="checkbox" checked={sel.has(f.id)} readOnly/>
                    </span>
                    <Icon name="folder" size={13} style={{color:'var(--fg-3)'}}/>
                    <span className="rp-row__name">{f.name}</span>
                    <div style={{flex:1}}/>
                    <span className="muted mono" style={{fontSize:10.5}}>{f.suiteCount} suites · {f.tcCount} TCs</span>
                  </label>
                ))}
              </div>
            )}

            {/* Mode: suite → grouped by feature */}
            {mode === "suite" && (
              <div className="rp-list">
                {MOCK_FEATURES.filter(f => MOCK_SUITES.some(s => s.feature_id === f.id)).map(f => {
                  const suites = MOCK_SUITES.filter(s => s.feature_id === f.id);
                  const allOn = suites.every(s => sel.has(s.id));
                  const someOn = suites.some(s => sel.has(s.id)) && !allOn;
                  const isCollapsed = collapsed[f.id];
                  return (
                    <div key={f.id} className="rp-group">
                      <div className="rp-group__h">
                        <button className="rp-group__chev" onClick={() => setCollapsed(c => ({...c, [f.id]: !c[f.id]}))}>
                          <Icon name={isCollapsed ? "chevronRight" : "chevronDown"} size={11}/>
                        </button>
                        <Icon name="folder" size={12} style={{color:'var(--fg-3)'}}/>
                        <span className="rp-group__name">{f.name}</span>
                        <span className="muted mono" style={{fontSize:10.5}}>{suites.length}</span>
                        <div style={{flex:1}}/>
                        <button className="link-btn">{allOn ? "Deselect all" : "Select all in group"}</button>
                      </div>
                      {!isCollapsed && suites.map(s => (
                        <label key={s.id} className={"rp-row rp-row--nested" + (sel.has(s.id) ? " rp-row--on" : "")} onClick={(e) => { e.preventDefault(); toggle(s.id); }}>
                          <span className="rp-row__check"><input type="checkbox" checked={sel.has(s.id)} readOnly/></span>
                          <Icon name="layers" size={12} style={{color:'var(--fg-3)'}}/>
                          <span className="rp-row__name">{s.name}</span>
                          <div style={{flex:1}}/>
                          <span className="muted mono" style={{fontSize:10.5}}>{s.tcCount} TCs</span>
                        </label>
                      ))}
                    </div>
                  );
                })}
              </div>
            )}

            {/* Mode: tc_list → grouped feature → suite → TC */}
            {mode === "tc_list" && (
              <div className="rp-list">
                {MOCK_FEATURES.filter(f => MOCK_TCS.some(t => t.feature_id === f.id)).map(f => {
                  const fTCs = MOCK_TCS.filter(t => t.feature_id === f.id);
                  const isCollapsed = collapsed[f.id];
                  const suites = MOCK_SUITES.filter(s => s.feature_id === f.id && fTCs.some(t => t.suite_id === s.id));
                  return (
                    <div key={f.id} className="rp-group">
                      <div className="rp-group__h">
                        <button className="rp-group__chev" onClick={() => setCollapsed(c => ({...c, [f.id]: !c[f.id]}))}>
                          <Icon name={isCollapsed ? "chevronRight" : "chevronDown"} size={11}/>
                        </button>
                        <Icon name="folder" size={12} style={{color:'var(--fg-3)'}}/>
                        <span className="rp-group__name">{f.name}</span>
                        <span className="muted mono" style={{fontSize:10.5}}>{fTCs.length} TCs</span>
                        <div style={{flex:1}}/>
                        <button className="link-btn">Select all {fTCs.length}</button>
                      </div>
                      {!isCollapsed && suites.map(s => {
                        const sTCs = fTCs.filter(t => t.suite_id === s.id);
                        return (
                          <div key={s.id} className="rp-subgroup">
                            <div className="rp-subgroup__h">
                              <Icon name="layers" size={11} style={{color:'var(--fg-4)'}}/>
                              <span>{s.name}</span>
                              <span className="muted mono" style={{fontSize:10.5}}>{sTCs.length}</span>
                              <div style={{flex:1}}/>
                              <button className="link-btn" style={{fontSize:10.5}}>Select all in suite</button>
                            </div>
                            {sTCs.map(t => (
                              <label key={t.id} className={"rp-row rp-row--tc" + (sel.has(t.id) ? " rp-row--on" : "")} onClick={(e) => { e.preventDefault(); toggle(t.id); }}>
                                <span className="rp-row__check"><input type="checkbox" checked={sel.has(t.id)} readOnly/></span>
                                <span className={"dot " + t.status}/>
                                <span className="mono tag-id" style={{fontSize:10.5, minWidth:54}}>{t.id}</span>
                                <span className="rp-row__name rp-row__name--tc">{t.description}</span>
                              </label>
                            ))}
                          </div>
                        );
                      })}
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

// ─── Wrapper screens for each state ─────────────────────────────────
const RPModalShell = ({ children, title = "Edit trigger", subtitle = "Refs picker" }) => (
  <div className="frame app" style={{position:'relative'}} data-theme="dark">
    {window.TopBar && <window.TopBar/>}
    <div style={{flex:1, opacity:0.32, pointerEvents:'none'}}>
      {window.Sidebar && <div className="board"><window.Sidebar/><div className="tc"/></div>}
    </div>
    <div className="modal-host">
      <div className="modal-back"/>
      <div className="modal modal--rp">
        <header className="modal__h">
          <div>
            <div className="modal__title"><Icon name="branch" size={13}/>{title}</div>
            <div className="modal__sub muted">{subtitle}</div>
          </div>
          <div style={{flex:1}}/>
          <button className="btn btn--ghost"><Icon name="x" size={12}/></button>
        </header>
        <div className="rp-modal-body">
          <div className="rp-form-summary">
            <div className="kv-line"><span className="muted">Repo</span><span className="mono">acme/api</span></div>
            <div className="kv-line"><span className="muted">Branch</span><span className="mono">main</span></div>
            <div className="kv-line"><span className="muted">Events</span><span className="ev-tag">push</span><span className="ev-tag">pull_request</span></div>
            <div className="kv-line"><span className="muted">Env</span><span className="env-pill" style={{height:18, fontSize:10}}><span className="env-pill__dot" style={{background:'oklch(0.78 0.13 230)'}}/>staging</span></div>
          </div>
          {children}
        </div>
        <footer className="modal__f">
          <span className="muted mono" style={{fontSize:10.5}}>test_selection.refs · saved as string[]</span>
          <div style={{flex:1}}/>
          <button className="btn btn--ghost">Cancel</button>
          <button className="btn btn--primary">Save trigger</button>
        </footer>
      </div>
    </div>
  </div>
);

const RPDefault = () => {
  const [refs, setRefs] = React.useState(["f_gift", "f_wallet"]);
  return <RPModalShell title="Edit trigger · Mode: feature" subtitle="Default state — flat feature list">
    <RefsPicker mode="feature" selectedRefs={refs} onChange={setRefs}/>
  </RPModalShell>;
};

const RPSuiteMode = () => {
  const [refs, setRefs] = React.useState(["s_sell", "s_inv", "s_bal"]);
  return <RPModalShell title="Edit trigger · Mode: suite" subtitle="Grouped by feature with collapse">
    <RefsPicker mode="suite" selectedRefs={refs} onChange={setRefs}/>
  </RPModalShell>;
};

const RPTcMode = () => {
  const [refs, setRefs] = React.useState(["TC-004", "TC-005", "TC-018", "TC-101"]);
  return <RPModalShell title="Edit trigger · Mode: tc_list" subtitle="Two-level hierarchy · feature → suite → TC">
    <RefsPicker mode="tc_list" selectedRefs={refs} onChange={setRefs}/>
  </RPModalShell>;
};

const RPSearch = () => {
  return <RPModalShell title="Edit trigger · Search active" subtitle="Filtering with 'sell' query">
    <RefsPicker mode="tc_list" selectedRefs={["TC-004"]} onChange={() => {}} state="search"/>
  </RPModalShell>;
};

const RPValidation = () => {
  return <RPModalShell title="Edit trigger · Validation error" subtitle="User tried to submit with 0 selected">
    <RefsPicker mode="feature" selectedRefs={[]} onChange={() => {}} state="validation"/>
  </RPModalShell>;
};

const RPLoading = () => (
  <RPModalShell title="Edit trigger · Loading" subtitle="Fetching catalog from /api/features">
    <RefsPicker mode="feature" selectedRefs={[]} onChange={() => {}} state="loading"/>
  </RPModalShell>
);

const RPEmpty = () => (
  <RPModalShell title="Edit trigger · Empty catalog" subtitle="Workspace has no features yet">
    <RefsPicker mode="feature" selectedRefs={[]} onChange={() => {}} state="empty"/>
  </RPModalShell>
);

const RPNoMatch = () => (
  <RPModalShell title="Edit trigger · No search match" subtitle="Query returned 0 results">
    <RefsPicker mode="tc_list" selectedRefs={[]} onChange={() => {}} state="no-match"/>
  </RPModalShell>
);

const RPError = () => (
  <RPModalShell title="Edit trigger · API error" subtitle="Backend unreachable">
    <RefsPicker mode="feature" selectedRefs={[]} onChange={() => {}} state="error"/>
  </RPModalShell>
);

// Mobile bottom-sheet variant
const RPMobile = () => {
  const [refs, setRefs] = React.useState(["f_gift"]);
  return (
    <div className="frame" style={{background:'var(--bg)', display:'flex', alignItems:'flex-end', justifyContent:'center', height:'100%'}} data-theme="dark">
      <div style={{position:'absolute', inset:0, background:'rgba(0,0,0,0.5)'}}/>
      <div className="rp-sheet">
        <div className="rp-sheet__grab"/>
        <div className="rp-sheet__h">
          <div>
            <div style={{fontSize:14, fontWeight:600}}>Pick features</div>
            <div className="muted" style={{fontSize:11.5}}>Trigger fires on every TC inside</div>
          </div>
          <div style={{flex:1}}/>
          <button className="btn btn--ghost"><Icon name="x" size={13}/></button>
        </div>
        <div style={{padding: '0 4px', flex:1, overflow:'auto'}}>
          <RefsPicker mode="feature" selectedRefs={refs} onChange={setRefs}/>
        </div>
        <div className="rp-sheet__f">
          <button className="btn btn--ghost" style={{flex:1}}>Cancel</button>
          <button className="btn btn--primary" style={{flex:2}}>Save · {refs.length} selected</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { RefsPicker, RPDefault, RPSuiteMode, RPTcMode, RPSearch, RPValidation, RPLoading, RPEmpty, RPNoMatch, RPError, RPMobile });
