// Source on its own row (compact, light-green active).
// Type + query on row 2.
// Row 3 = compact status + reveal triggers (left) + cache controls (right).
// Reveal content (raw JSON / metadata) expands inline below row 3.

function SearchBar({
  source, onSourceChange,
  type, onTypeChange,
  query, onQueryChange,
  onSearch, onReset, loading,
  cache, onRefresh, onClearCache,
  param, onParamChange,
  statusText,
  detailMode,
  view, onView,
  rawJson, metadata
}) {
  const types = source === "FILE" ? FILE_TYPES : SNB_TYPES;
  const [open, setOpen] = React.useState(null); // "raw" | "meta" | null

  // Close reveal whenever we leave detail mode
  React.useEffect(() => { if (!detailMode) setOpen(null); }, [detailMode]);

  return (
    <div className="pv-searchbar" data-screen-label="Search bar">
      {/* Row 1 — Source (compact) */}
      <div className="pv-searchbar-source-row">
        <span className="pv-field-label">Source</span>
        <div className="pv-segmented" role="tablist">
          <button role="tab" aria-selected={source === "FILE"}
            className={cx("pv-segmented-opt", source === "FILE" && "is-active")}
            onClick={() => onSourceChange("FILE")}>FILE</button>
          <button role="tab" aria-selected={source === "SNB"}
            className={cx("pv-segmented-opt", source === "SNB" && "is-active")}
            onClick={() => onSourceChange("SNB")}>SNB</button>
        </div>
        <span className="pv-source-hint">{source === "FILE" ? "GitHub onboarding repos" : "Internal product catalog API"}</span>
      </div>

      {/* Row 2 — Type + query */}
      <div className="pv-searchbar-row">
        <Select value={type} onChange={(e) => onTypeChange(e.target.value)} style={{ width: 'auto', flexShrink: 0 }} className="pv-select-compact">
          {types.map(t => <option key={t} value={t}>{t}</option>)}
        </Select>
        <div className="pv-search-input-wrap">
          <span className="pv-search-input-icon"><Icon name="search" size={14} /></span>
          <Input
            className="pv-search-input pv-search-input-compact"
            placeholder={source === "FILE" ? "ID, name or path…" : "e.g. PO-001"}
            value={query}
            onChange={(e) => onQueryChange(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && onSearch()}
          />
          {query && (
            <button className="pv-search-input-clear" onClick={() => onQueryChange("")} aria-label="Clear">
              <Icon name="x" size={12} />
            </button>
          )}
        </div>
        <Button variant="primary" size="sm" onClick={onSearch} disabled={loading}>
          {loading ? <Icon name="loader" /> : <Icon name="search" />} {loading ? 'Searching…' : 'Search'}
        </Button>
        <Button variant="secondary" size="sm" onClick={onReset}>Reset</Button>
      </div>

      {/* Row 3 — status (left) · graph view (center) · cache controls (right) */}
      <div className="pv-searchbar-row2">
        <div className="left">
          <span className="pv-status-text">{statusText || "Ready."}</span>
          {detailMode && (
            <>
              <span className="pv-mini-sep">·</span>
              <button className={cx("pv-mini-btn", open === "raw" && "is-open")} onClick={() => setOpen(o => o === "raw" ? null : "raw")}>
                Raw JSON <Icon name="chevron-down" size={10} />
              </button>
              <button className={cx("pv-mini-btn", open === "meta" && "is-open")} onClick={() => setOpen(o => o === "meta" ? null : "meta")}>
                Metadata <Icon name="chevron-down" size={10} />
              </button>
            </>
          )}
        </div>
        <div className="center">
          {detailMode && (
            <button
              className={cx("pv-mini-btn pv-graph-toggle", view === "graph" && "is-open")}
              onClick={() => onView(view === "graph" ? "table" : "graph")}
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="5" cy="12" r="2"/><circle cx="19" cy="5" r="2"/><circle cx="19" cy="19" r="2"/>
                <line x1="7" y1="12" x2="17" y2="6"/><line x1="7" y1="12" x2="17" y2="18"/>
              </svg>
              Graph View
            </button>
          )}
        </div>
        <div className="right">
          {source === "SNB" && type === "productOfferingPrices" && (
            <>
              <span style={{ fontSize: 11, color: "var(--fg-3)" }}>Param:</span>
              <select className="inline-select" value={param} onChange={(e) => onParamChange(e.target.value)}>
                <option>productOfferingName</option>
                <option>prodOfferProdOfferPriceId</option>
              </select>
              <span className="pv-mini-sep">·</span>
            </>
          )}
          <Button variant="secondary" size="sm" onClick={onRefresh}>Refresh</Button>
          <Button variant="secondary" size="sm" onClick={onClearCache}>Clear Cache</Button>
        </div>
      </div>

      {/* Inline reveal */}
      {detailMode && open === "raw" && (
        <div className="pv-reveal-inline">
          <div className="pv-reveal-head">
            <span>Raw JSON</span>
            <Button variant="secondary" size="sm" onClick={() => {
              navigator.clipboard && navigator.clipboard.writeText(JSON.stringify(rawJson, null, 2));
            }}>
              <Icon name="copy" size={12} /> Copy
            </Button>
          </div>
          <pre>{JSON.stringify(rawJson, null, 2)}</pre>
        </div>
      )}
      {detailMode && open === "meta" && (
        <div className="pv-reveal-inline">
          <ul>
            {Object.entries(metadata || {}).map(([k, v]) => (
              <li key={k}><b>{k}</b>{String(v)}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { SearchBar });
