// itrymo — Mobile + Web variants using TagInput + CompactSort

// ─────────────────────────────────────────────────────────────
// Mobile variant — Refine sheet uses per-category tag inputs
// ─────────────────────────────────────────────────────────────
function MobileAppInputs({ city = 'Seoul' }) {
  const [bucket, setBucket] = React.useState('eat');
  const [tags, setTags] = React.useState(['Coffee', 'Japanese']);
  const [sort, setSort] = React.useState('recommended');
  const [sheetOpen, setSheetOpen] = React.useState(true); // demo open by default

  const switchBucket = (id) => { setBucket(id); setTags([]); };
  const toggleTag = (tg) => setTags((cur) => cur.includes(tg) ? cur.filter((t) => t !== tg) : [...cur, tg]);

  const groups = getGroupsFor(bucket);
  const filtered = sortPlaces(applyFilters(PLACES, { bucket, tags }), sort);
  const sortLabel = (SORTS.find((s) => s.id === sort) || {}).label || 'Must try';
  const tagCounts = React.useMemo(() => getTagCounts(PLACES), []);

  const summary = tags.length === 0
    ? 'All tags'
    : tags.slice(0, 2).join(', ') + (tags.length > 2 ? ` +${tags.length - 2}` : '');

  return (
    <div style={{
      width: '100%', height: '100%', background: T.bg,
      fontFamily: T.fontUI, color: T.ink,
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <div style={{ height: 54 }} />
      <div style={{ padding: '4px 20px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 500, color: T.muted, letterSpacing: 0.4, textTransform: 'uppercase' }}>{city} · Today</div>
          <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, marginTop: 2 }}>Discover</div>
        </div>
        <div style={{
          width: 36, height: 36, borderRadius: 18, background: '#fff',
          border: `1px solid ${T.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="map" size={16} /></div>
      </div>

      <div style={{ padding: '0 20px', display: 'flex', gap: 6 }}>
        {BUCKETS.map((b) => {
          const on = b.id === bucket;
          return (
            <button key={b.id} onClick={() => switchBucket(b.id)} style={{
              all: 'unset', cursor: 'pointer',
              flex: 1, height: 46, borderRadius: 12,
              background: on ? T.selBg : '#fff',
              color: on ? T.selFg : T.faintInk,
              border: `1px solid ${on ? T.selBg : T.border}`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3,
            }}>
              <Icon name={b.icon} size={14} />
              <div style={{ fontSize: 11, fontWeight: 600 }}>{b.label}</div>
            </button>
          );
        })}
      </div>

      <div style={{ padding: '10px 20px 0' }}>
        <button onClick={() => setSheetOpen(true)} style={{
          all: 'unset', cursor: 'pointer',
          width: '100%', height: 40, borderRadius: 12, background: '#fff',
          border: `1px solid ${T.border}`, boxSizing: 'border-box',
          display: 'flex', alignItems: 'center', padding: '0 12px', gap: 8,
        }}>
          <Icon name="filter" size={13} color={tags.length ? T.accent : T.muted} />
          <span style={{ fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', flexShrink: 0 }}>
            {tags.length === 0 ? 'Refine' : `${tags.length} ${tags.length === 1 ? 'tag' : 'tags'}`}
          </span>
          {tags.length > 0 && (
            <span style={{
              fontSize: 12, color: T.muted, minWidth: 0, flex: 1,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>· {summary}</span>
          )}
          <span style={{
            marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6,
            color: T.muted, fontSize: 12, whiteSpace: 'nowrap', flexShrink: 0,
          }}>
            <Icon name="sort" size={11} /> {sortLabel}
          </span>
        </button>
      </div>

      <div style={{ flex: 1, position: 'relative', marginTop: 12, overflow: 'hidden' }}>
        <div style={{
          height: '100%', overflowY: 'auto',
          padding: '0 20px 28px', display: 'flex', flexDirection: 'column', gap: 12,
          opacity: sheetOpen ? 0.45 : 1, transition: 'opacity .15s',
          pointerEvents: sheetOpen ? 'none' : 'auto',
        }}>
          {filtered.map((p) => (
            <PlaceCard key={p.id} place={p} variant="wide" activeTags={tags} onTag={toggleTag} />
          ))}
        </div>

        {sheetOpen && (
          <InputRefineSheet
            bucket={bucket} groups={groups} tags={tags} toggleTag={toggleTag}
            sort={sort} setSort={setSort}
            tagCounts={tagCounts}
            count={filtered.length}
            onClear={() => setTags([])} onClose={() => setSheetOpen(false)}
          />
        )}
      </div>
    </div>
  );
}

function InputRefineSheet({ bucket, groups, tags, toggleTag, sort, setSort, tagCounts, count, onClear, onClose }) {
  const bucketLabel = (BUCKETS.find((b) => b.id === bucket) || {}).label || '';
  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(0,0,0,0.04) 0%, rgba(0,0,0,0.18) 70%)',
      }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: T.panel, borderTopLeftRadius: 22, borderTopRightRadius: 22,
        boxShadow: '0 -12px 36px rgba(0,0,0,0.10)',
        padding: '10px 18px 18px',
        maxHeight: '90%', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ width: 38, height: 4, borderRadius: 2, background: '#D9D2C5', margin: '4px auto 12px' }} />

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ fontSize: 15, fontWeight: 700, whiteSpace: 'nowrap' }}>
            Refine <span style={{ color: T.muted, fontWeight: 500 }}>· {bucketLabel}</span>
          </div>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            {tags.length > 0 && (
              <button onClick={onClear} style={{
                all: 'unset', cursor: 'pointer', fontSize: 12, color: T.accent, fontWeight: 600,
              }}>Clear all</button>
            )}
            <button onClick={onClose} style={{
              all: 'unset', cursor: 'pointer',
              width: 28, height: 28, borderRadius: 14, background: '#F4EFE6',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="close" size={13} /></button>
          </div>
        </div>

        <div style={{ overflowY: 'auto', flex: 1, minHeight: 0, marginRight: -8, paddingRight: 8 }}>
          {/* Sort — segmented */}
          <div style={{
            fontSize: 10, color: T.muted, letterSpacing: 0.6,
            textTransform: 'uppercase', fontWeight: 700, marginBottom: 6,
          }}>Sort</div>
          <Segmented
            options={SORTS.map((s) => ({ id: s.id, label: s.label }))}
            value={sort} onChange={setSort} size="sm"
          />
          <div style={{ fontSize: 11, color: T.muted, marginTop: 6 }}>
            {(SORTS.find((s) => s.id === sort) || {}).hint}
          </div>

          {/* One input per group */}
          <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 16 }}>
            {groups.map((g) => (
              <TagInput
                key={g.id}
                groupLabel={g.label}
                tags={g.tags}
                selected={tags.filter((t) => g.tags.includes(t))}
                onToggle={toggleTag}
                tagCounts={tagCounts}
                placeholder={inputPlaceholder(g)}
              />
            ))}
          </div>
        </div>

        <button onClick={onClose} style={{
          all: 'unset', cursor: 'pointer',
          marginTop: 12, width: '100%', height: 46, borderRadius: 12,
          background: T.selBg, color: T.selFg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 600,
        }}>
          Show {count} {count === 1 ? 'place' : 'places'}
        </button>
      </div>
    </>
  );
}

function inputPlaceholder(g) {
  // Use first 2-3 tags as placeholder example
  const sample = g.tags.slice(0, 3).join(', ');
  return `e.g. ${sample}…`;
}

// ─────────────────────────────────────────────────────────────
// Web variant — sidebar uses TagInput per group + CompactSort top-right
// ─────────────────────────────────────────────────────────────
function WebAppInputs({ city = 'Seoul' }) {
  const [bucket, setBucket] = React.useState('eat');
  const [tags, setTags] = React.useState(['Coffee', 'Japanese']);
  const [sort, setSort] = React.useState('recommended');

  const switchBucket = (id) => { setBucket(id); setTags([]); };
  const toggleTag = (tg) => setTags((cur) => cur.includes(tg) ? cur.filter((t) => t !== tg) : [...cur, tg]);

  const groups = getGroupsFor(bucket);
  const filtered = sortPlaces(applyFilters(PLACES, { bucket, tags }), sort);
  const tagCounts = React.useMemo(() => getTagCounts(PLACES), []);

  return (
    <div style={{
      width: '100%', minHeight: '100%', background: T.bg,
      fontFamily: T.fontUI, color: T.ink,
    }}>
      <div style={{
        height: 60, background: '#fff', borderBottom: `1px solid ${T.border}`,
        display: 'flex', alignItems: 'center', padding: '0 28px', gap: 20,
        position: 'sticky', top: 0, zIndex: 30,
      }}>
        <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: -0.5, display: 'flex', alignItems: 'center', gap: 6 }}>
          itrymo<span style={{ color: T.accent }}>.</span>
          <span style={{ fontSize: 10, fontWeight: 600, color: '#B36A00', background: '#FFF3E0', border: '1px solid #F5C97A', borderRadius: 20, padding: '1px 7px', letterSpacing: 0.2 }}>Beta</span>
        </div>
        <button style={{
          all: 'unset', cursor: 'pointer',
          height: 36, padding: '0 12px', borderRadius: 10, border: `1px solid ${T.border}`,
          display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 500,
        }}>
          <Icon name="pin" size={13} color={T.accent} /> {city}
          <Icon name="chev" size={11} color={T.muted} />
        </button>
        <div style={{
          flex: 1, maxWidth: 420, height: 38, borderRadius: 10,
          background: T.bg, border: `1px solid ${T.border}`,
          display: 'flex', alignItems: 'center', padding: '0 12px', gap: 8,
        }}>
          <Icon name="search" size={14} color={T.muted} />
          <span style={{ color: T.muted, fontSize: 13 }}>Search places, tags, neighborhoods…</span>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 14 }}>
          <button style={{ all: 'unset', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: T.faintInk }}>Trips</button>
          <button style={{ all: 'unset', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: T.faintInk }}>Saved</button>
          <div style={{
            width: 34, height: 34, borderRadius: 17, background: T.accentBg,
            color: T.accent, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 12, fontWeight: 700,
          }}>JL</div>
        </div>
      </div>

      <div style={{ background: '#fff', borderBottom: `1px solid ${T.border}`, padding: '18px 28px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {BUCKETS.map((b) => {
            const on = b.id === bucket;
            return (
              <button key={b.id} onClick={() => switchBucket(b.id)} style={{
                all: 'unset', cursor: 'pointer',
                height: 44, padding: '0 18px', borderRadius: 12,
                background: on ? T.selBg : T.bg,
                color: on ? T.selFg : T.faintInk,
                border: `1px solid ${on ? T.selBg : T.border}`,
                display: 'inline-flex', alignItems: 'center', gap: 8,
                fontSize: 14, fontWeight: 600,
              }}>
                <Icon name={b.icon} size={15} />
                <span>{b.label}</span>
                <span style={{ fontSize: 11, fontWeight: 500, opacity: 0.6 }}>{b.desc}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 24, padding: '24px 28px 60px', alignItems: 'flex-start' }}>
        <aside style={{
          position: 'sticky', top: 84,
          background: '#fff', borderRadius: 16, border: `1px solid ${T.borderSoft}`,
          padding: 18,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 700 }}>Refine</div>
            {tags.length > 0 && (
              <button onClick={() => setTags([])} style={{
                all: 'unset', cursor: 'pointer', fontSize: 12, color: T.accent, fontWeight: 600,
              }}>Clear all</button>
            )}
          </div>

          {/* Sort — segmented */}
          <div style={{
            fontSize: 10, color: T.muted, letterSpacing: 0.6,
            textTransform: 'uppercase', fontWeight: 700, marginBottom: 6,
          }}>Sort</div>
          <Segmented
            options={SORTS.map((s) => ({ id: s.id, label: s.label }))}
            value={sort} onChange={setSort} size="sm"
          />
          <div style={{ fontSize: 11, color: T.muted, marginTop: 6, marginBottom: 16 }}>
            {(SORTS.find((s) => s.id === sort) || {}).hint}
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxHeight: 540, overflowY: 'auto', marginRight: -6, paddingRight: 6 }}>
            {groups.map((g) => (
              <TagInput
                key={g.id}
                groupLabel={g.label}
                tags={g.tags}
                selected={tags.filter((t) => g.tags.includes(t))}
                onToggle={toggleTag}
                tagCounts={tagCounts}
                placeholder={inputPlaceholder(g)}
              />
            ))}
          </div>
        </aside>

        <main>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            gap: 16, marginBottom: 16, flexWrap: 'wrap',
          }}>
            <div style={{ fontSize: 13, color: T.muted }}>
              <strong style={{ color: T.ink, fontSize: 16, fontWeight: 700, marginRight: 6 }}>{filtered.length}</strong>
              places in {city}
            </div>
          </div>

          {filtered.length === 0 ? (
            <div style={{
              padding: '60px 20px', textAlign: 'center', color: T.muted, fontSize: 14,
              background: '#fff', borderRadius: 16, border: `1px dashed ${T.border}`,
            }}>No places match. Try removing a tag.</div>
          ) : (
            <div style={{
              display: 'grid', gap: 16,
              gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
            }}>
              {filtered.map((p) => (
                <PlaceCard key={p.id} place={p} variant="grid" activeTags={tags} onTag={toggleTag} />
              ))}
            </div>
          )}
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { MobileAppInputs, WebAppInputs, InputRefineSheet });
