// ─────────────────────────────────────────────────────────────
// Forest search — analogous to the Folk-tab search (folk_prototype's
// Search.jsx). Flat results view, multiple buckets, plus a fallback
// "Plant a forest called X" CTA at the bottom.
//
// Buckets:
//   1 · In your forests — matches the user is already a member of.
//   2 · Discoverable    — public/open forests, not yet joined.
//   3 · Across the canopy — invite-only / private spaces with no
//                            overlap; info-limited per privacy rules.
//   4 · Matching leaves — branch content matches; quoted snippets.
//
// Plus a "Plant a forest called …" tile that builds the create flow
// pre-seeded with the query.
// ─────────────────────────────────────────────────────────────


// ─── Search bar (matches the Folk SearchBar shape) ───
function ForestSearchBar({ value, onChange, onClear, autoFocus = false }) {
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (autoFocus) inputRef.current?.focus(); }, [autoFocus]);
  return (
    <div style={{ padding: '0 18px 10px', flexShrink: 0 }}>
      <div style={{
        height: 42, padding: '0 12px',
        background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10,
        display: 'flex', alignItems: 'center', gap: 10,
        transition: 'border-color 160ms var(--ease-organic)',
      }}>
        <FLIcons.Search size={16} color="#586552"/>
        <input
          ref={inputRef}
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder="Find a forest, leaf, or topic"
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            font: '500 14px var(--font-sans)', color: '#F2EDE4',
          }}/>
        {value && (
          <button onClick={onClear} aria-label="Clear search"
            style={{
              background: 'transparent', border: 'none', padding: 4, color: '#586552',
              cursor: 'pointer', display: 'flex',
            }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
            </svg>
          </button>
        )}
      </div>
    </div>
  );
}


// ─── Across-the-canopy synthetic results (no overlap with user) ───
const CANOPY_FORESTS = [
  { id: 'cc1', name: 'Cycling · Yorkshire Dales', kind: 'invite', join: 'referral',
    members: 211, blurb: 'wet roads, big climbs, slow tea.', whereabouts: 'in another canopy' },
  { id: 'cc2', name: 'Track Cyclists Anonymous', kind: 'invite', join: 'moderated',
    members: 88, blurb: 'velodrome talk, no road posts.', whereabouts: 'invite-only' },
];

// ─── Leaves whose branch text matches the query (search across forests) ───
function leavesMatching(q) {
  if (!q) return [];
  const lq = q.toLowerCase();
  return VIRAL_LEAVES.filter(v =>
    v.branch.toLowerCase().includes(lq) ||
    v.rootSnippet.toLowerCase().includes(lq) ||
    v.forest.toLowerCase().includes(lq)
  );
}


function ForestSearchResults({ query, onTapForest = () => {}, onTapJoin = () => {},
                               onPlantNew = () => {} }) {
  const q = query.trim();
  const lq = q.toLowerCase();

  const matchedYours = YOUR_FORESTS.filter(f =>
    f.name.toLowerCase().includes(lq) || f.blurb.toLowerCase().includes(lq));
  const matchedDiscover = DISCOVER_FORESTS.filter(f =>
    f.name.toLowerCase().includes(lq) || f.blurb.toLowerCase().includes(lq));
  const matchedCanopy = CANOPY_FORESTS.filter(f =>
    f.name.toLowerCase().includes(lq) || f.blurb.toLowerCase().includes(lq));
  const matchedLeaves = leavesMatching(q);

  const total = matchedYours.length + matchedDiscover.length +
                matchedCanopy.length + matchedLeaves.length;

  return (
    <div style={{ padding: '4px 0 24px' }}>
      {total === 0 && q.length > 0 && <ForestSearchEmpty query={q} onPlantNew={onPlantNew}/>}

      {matchedYours.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <ForestSectionLabel>In your forests · {matchedYours.length}</ForestSectionLabel>
          <LeafStagger staggerMs={45}
            style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8 }}>
            {matchedYours.map(f => (
              <YoursSearchRow key={f.id} f={f} q={q} onTap={() => onTapForest(f)}/>
            ))}
          </LeafStagger>
        </div>
      )}

      {matchedDiscover.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <ForestSectionLabel>Discoverable · {matchedDiscover.length}</ForestSectionLabel>
          <div style={{ font: 'italic 400 12px var(--font-serif)',
                        color: '#586552', marginTop: 2, marginBottom: 8 }}>
            Public forests you haven't joined. Tap to preview.
          </div>
          <LeafStagger staggerMs={45}
            style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {matchedDiscover.map(f => (
              <DiscoverableSearchRow key={f.id} f={f} q={q}
                onTap={() => onTapForest(f)}
                onJoin={(e) => { e.stopPropagation(); onTapJoin(f); }}/>
            ))}
          </LeafStagger>
        </div>
      )}

      {matchedCanopy.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <ForestSectionLabel>Across the canopy · {matchedCanopy.length}</ForestSectionLabel>
          <div style={{ font: 'italic 400 12px var(--font-serif)',
                        color: '#586552', marginTop: 2, marginBottom: 8 }}>
            Invite-only spaces with no overlap. Details show after a steward lets you in.
          </div>
          <LeafStagger staggerMs={45}
            style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {matchedCanopy.map(f => <CanopySearchRow key={f.id} f={f} q={q}/>)}
          </LeafStagger>
        </div>
      )}

      {matchedLeaves.length > 0 && (
        <div style={{ padding: '6px 18px 14px' }}>
          <ForestSectionLabel>Matching leaves · {matchedLeaves.length}</ForestSectionLabel>
          <div style={{ font: 'italic 400 12px var(--font-serif)',
                        color: '#586552', marginTop: 2, marginBottom: 8 }}>
            Branches where this came up.
          </div>
          <LeafStagger staggerMs={45}
            style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {matchedLeaves.map(v => <LeafSearchRow key={v.id} v={v} q={q}/>)}
          </LeafStagger>
        </div>
      )}

      {/* Plant-a-forest fallback CTA — always available, mirrors
          Trade-handles in folk search. Shown only when there's a query. */}
      {q.length > 0 && (
        <div style={{ padding: '4px 18px 0' }}>
          <button onClick={onPlantNew}
            style={{
              width: '100%',
              background: '#111D0A', border: '0.5px solid #2D3A22',
              borderRadius: 12, padding: '12px 14px',
              display: 'flex', alignItems: 'center', gap: 12,
              cursor: 'pointer', textAlign: 'left',
              transition: 'background 140ms var(--ease-organic)',
            }}
            onMouseEnter={e => e.currentTarget.style.background = '#162310'}
            onMouseLeave={e => e.currentTarget.style.background = '#111D0A'}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: '#1B3A1D', border: '0.5px solid #2C5F2E',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <FLIcons.Pencil size={16} color="#A8C5A0"/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ font: '500 14px var(--font-sans)', color: '#F2EDE4' }}>
                Plant a forest called <span style={{ fontFamily: 'var(--font-mono)' }}>"{q}"</span>
              </div>
              <div style={{ font: 'italic 400 12px var(--font-serif)', color: '#8A9678', marginTop: 2 }}>
                If nobody's started this place yet, you could.
              </div>
            </div>
            <span style={{ color: '#586552', display: 'flex' }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="m9 18 6-6-6-6"/>
              </svg>
            </span>
          </button>
        </div>
      )}

      {q.length === 0 && <ForestSearchHints/>}
    </div>
  );
}


function ForestSectionLabel({ children }) {
  return (
    <div style={{
      font: '500 10.5px var(--font-sans)', color: '#76AB78',
      letterSpacing: '0.12em', textTransform: 'uppercase',
    }}>{children}</div>
  );
}


// Highlight occurrences of `q` in text. Subtle — sunlight tint, not a hammer.
function Highlight({ text = '', q = '' }) {
  if (!q) return <>{text}</>;
  const lq = q.toLowerCase();
  const parts = [];
  let i = 0;
  const lower = text.toLowerCase();
  while (i < text.length) {
    const idx = lower.indexOf(lq, i);
    if (idx === -1) { parts.push(text.slice(i)); break; }
    parts.push(text.slice(i, idx));
    parts.push(
      <mark key={parts.length} style={{
        background: 'rgba(212,150,12,0.18)', color: '#F4DCA0',
        padding: '0 2px', borderRadius: 3,
      }}>{text.slice(idx, idx + q.length)}</mark>
    );
    i = idx + q.length;
  }
  return <>{parts}</>;
}


// ── Row variants ──

function YoursSearchRow({ f, q, onTap }) {
  const isPrivate = f.kind === 'private';
  const intensity = forestIntensity(f);
  return (
    <RowAmbience seed={f.id} intensity={intensity} borderRadius={10}>
    <button onClick={onTap} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px',
      background: '#111D0A',
      border: '0.5px solid #1F2B16',
      borderLeft: isPrivate ? '2px solid #7A4F2D' : '0.5px solid #1F2B16',
      borderRadius: 10, width: '100%', cursor: 'pointer', textAlign: 'left',
    }}>
      <BreathingForestGlyph size={30} hot={f.activeNow > 5} intensity={intensity}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ font: '500 14px var(--font-sans)', color: '#F2EDE4' }}>
            <Highlight text={f.name} q={q}/>
          </span>
          <KindChip kind={f.kind}/>
        </div>
        <div style={{ font: 'italic 400 11.5px var(--font-serif)', color: '#8A9678', marginTop: 2 }}>
          <Highlight text={f.blurb} q={q}/>
        </div>
      </div>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '3px 8px', borderRadius: 999,
        background: 'rgba(94,128,72,0.10)',
        font: '500 10.5px var(--font-sans)', color: '#A8C5A0',
        letterSpacing: '0.04em', textTransform: 'uppercase',
      }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#5E8048' }}/>
        Member
      </span>
    </button>
    </RowAmbience>
  );
}


function DiscoverableSearchRow({ f, q, onTap, onJoin }) {
  const intensity = forestIntensity(f);
  return (
    <RowAmbience seed={f.id} intensity={intensity} borderRadius={10}>
    <div role="button" tabIndex={0} onClick={onTap}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '11px 12px',
        background: 'transparent',
        border: '0.5px dashed #2D3A22', borderRadius: 10,
        width: '100%', cursor: 'pointer', textAlign: 'left',
        boxSizing: 'border-box',
      }}>
      <ForestGlyph size={28} alive intensity={intensity}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ font: '500 14px var(--font-sans)', color: '#C9D2BB' }}>
            <Highlight text={f.name} q={q}/>
          </span>
          <JoinChip mode={f.join}/>
        </div>
        <div style={{ font: 'italic 400 11.5px var(--font-serif)', color: '#586552', marginTop: 2 }}>
          {fmtBig(f.members)} members · <Highlight text={f.blurb} q={q}/>
        </div>
      </div>
      {f.join === 'open'
        ? <Btn kind="primary" size="sm" onClick={onJoin}>Join</Btn>
        : <Btn kind="secondary" size="sm" onClick={onJoin}>Request</Btn>}
    </div>
    </RowAmbience>
  );
}


function CanopySearchRow({ f, q }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 12px',
      background: 'transparent',
      border: '0.5px solid #1F2B16', borderRadius: 10,
    }}>
      <div style={{ opacity: 0.55 }}>
        <ForestGlyph size={26} color="#586552"/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ font: '500 14px var(--font-sans)', color: '#A8C5A0' }}>
            <Highlight text={f.name} q={q}/>
          </span>
          <KindChip kind={f.kind}/>
        </div>
        <div style={{ font: 'italic 400 11.5px var(--font-serif)', color: '#586552', marginTop: 2 }}>
          {f.whereabouts}
        </div>
      </div>
      <span style={{
        font: '500 10.5px var(--font-sans)', color: '#586552',
        letterSpacing: '0.04em', textTransform: 'uppercase',
      }}>
        No overlap
      </span>
    </div>
  );
}


function LeafSearchRow({ v, q }) {
  return (
    <button style={{
      display: 'block', textAlign: 'left', width: '100%',
      padding: '11px 12px',
      background: '#111D0A', border: '0.5px solid #1F2B16', borderRadius: 10,
      cursor: 'pointer',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <ForestGlyph size={14} hot={v.signal !== 'quiet'}/>
        <span style={{ font: '500 11px var(--font-mono)', color: '#A8C5A0' }}>{v.forest}</span>
        <span style={{ font: '400 11px var(--font-sans)', color: '#586552' }}>·</span>
        <span style={{ font: '500 11px var(--font-mono)', color: '#C9D2BB' }}>{v.branchHandle}</span>
        <span style={{ flex: 1 }}/>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          font: '500 10px var(--font-mono)', color: '#F4DCA0',
        }}>
          <FLIcons.Sun size={10} color="#D4960C"/>{v.sunlight}
        </span>
      </div>
      <div style={{
        marginTop: 6, paddingLeft: 8, borderLeft: '2px solid #2D3A22',
        font: '400 12.5px/1.5 var(--font-sans)', color: '#C9D2BB',
      }}>
        <Highlight text={v.branch} q={q}/>
      </div>
    </button>
  );
}


function ForestSearchEmpty({ query, onPlantNew }) {
  return (
    <div style={{
      padding: '36px 32px 8px', textAlign: 'center',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: '#111D0A', border: '0.5px solid #2D3A22',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <FLIcons.Search size={22} color="#586552"/>
      </div>
      <div style={{ font: '500 15px var(--font-mono)', color: '#C9D2BB' }}>
        No forest named “{query}”.
      </div>
      <div style={{ font: 'italic 400 13px/1.55 var(--font-serif)', color: '#8A9678',
                    maxWidth: 260 }}>
        Try a partial name or a topic word — or plant the forest yourself, below.
      </div>
    </div>
  );
}


// Idle-state hints — recent searches + suggested topics. Mirrors how the
// folk-prototype shows Pulse strip while idle.
function ForestSearchHints() {
  return (
    <div style={{ padding: '6px 18px 14px' }}>
      <ForestSectionLabel>Recent</ForestSectionLabel>
      <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
        {['cycling', 'philosophy', 'BART', 'slow reading'].map(t => (
          <span key={t} style={{
            padding: '6px 11px',
            background: '#111D0A', border: '0.5px solid #1F2B16',
            borderRadius: 999, color: '#A8C5A0',
            font: '500 12px var(--font-mono)', cursor: 'pointer',
          }}>{t}</span>
        ))}
      </div>

      <div style={{ marginTop: 16 }}><ForestSectionLabel>Trending in your area · 4</ForestSectionLabel></div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8 }}>
        {DISCOVER_FORESTS.filter(f => f.signal === 'rising').slice(0, 4).map(f => (
          <div key={f.id} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 10px',
            background: '#0F1A09', border: '0.5px solid #1F2B16', borderRadius: 10,
          }}>
            <ForestGlyph size={22} hot/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ font: '500 13px var(--font-sans)', color: '#F2EDE4' }}>{f.name}</div>
              <div style={{ font: 'italic 400 11px var(--font-serif)', color: '#586552' }}>
                {f.blurb}
              </div>
            </div>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4,
                            font: '500 10.5px var(--font-mono)', color: '#F4DCA0' }}>
              <SignalDot signal="rising"/> rising
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}


// ─── Full Search screen (used as a takeover and as A1's "search" tab) ───
function ForestSearchScreen({ initialQuery = '', autoFocus = true, onBack, onPlantNew }) {
  const [q, setQ] = React.useState(initialQuery);
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
                  background: '#0B1306' }}>
      {/* Search header — back arrow + search bar */}
      <div style={{ flexShrink: 0, padding: '14px 18px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {onBack && (
            <button onClick={onBack}
              style={{ background: 'transparent', border: 'none', padding: 4,
                       color: '#A8C5A0', cursor: 'pointer', display: 'flex' }}
              aria-label="Back">
              <FLIcons.ChevronLeft size={20}/>
            </button>
          )}
          <div style={{ font: '500 10px var(--font-sans)', color: '#8A9678',
                        letterSpacing: '0.10em', textTransform: 'uppercase' }}>FORESTS · SEARCH</div>
        </div>
      </div>
      <div style={{ padding: '8px 0 0' }}>
        <ForestSearchBar value={q} onChange={setQ} onClear={() => setQ('')}
          autoFocus={autoFocus}/>
      </div>

      <PhoneBody style={{ paddingBottom: 80 }}>
        <ForestSearchResults query={q}
          onPlantNew={onPlantNew || (() => {})}/>
      </PhoneBody>

      <BottomNavFolk active="forests" hasNewSunlight={false}/>
    </div>
  );
}


Object.assign(window, {
  ForestSearchBar, ForestSearchResults, ForestSearchScreen,
  ForestSearchEmpty, ForestSearchHints,
});
