// ─── 바텀시트: 그룹 선택 ────────────────────────
function GroupSheet({
  group,
  groupId,
  parcelLookup,
  areas,
  colors,
  colorById,
  colorLabels,
  areaUnit,
  onAreaUnitChange,
  onSave,
  onDissolve,
  onAddParcels,
  onRemoveParcel,
  onClose,
  isPending,
  isWide,
}) {
  const colorList = colors || COLORS.map(c => ({ id: c.id, label: c.defaultLabel, hex: c.hex }));
  const colorMap  = colorById || COLOR_BY_ID;
  const openedAtRef = useRef(Date.now());

  const [draft, setDraft] = useState({
    name:  group.name  || '',
    memo:  group.memo  || '',
    color: group.color || null,
    style: group.style || 'fill',
  });

  useEffect(() => {
    setDraft({
      name:  group.name  || '',
      memo:  group.memo  || '',
      color: group.color || null,
      style: group.style || 'fill',
    });
  }, [groupId]);

  const memberParcels = (group.parcels || []).map(pid => parcelLookup[pid]).filter(Boolean);

  const totalArea = memberParcels.reduce((sum, p) => {
    const precise = areas[p.id]?.lndpcl_ar;
    return sum + (precise ?? p.area ?? 0);
  }, 0);

  const handleSave = () => {
    onSave({
      name:   draft.name.trim(),
      memo:   draft.memo.trim(),
      color:  draft.color,
      style:  draft.color ? draft.style : null,
      parcels: group.parcels || [],
    });
    onClose();
  };

  const content = (
    <React.Fragment>
      <div style={appStyles.sheetHeader}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={appStyles.sheetMeta}>그룹</div>
            <div style={appStyles.groupBadge}>
              <i data-lucide="layers" style={{ width: 10, height: 10 }}></i>
              {memberParcels.length}필지
            </div>
          </div>
          <button style={appStyles.closeX} onClick={onClose} aria-label="닫기">
            <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
          </button>
        </div>
        <input
          value={draft.name}
          onChange={(e) => setDraft(d => ({ ...d, name: e.target.value }))}
          placeholder="그룹 이름 입력"
          style={appStyles.nameInput}
        />
        {totalArea > 0 && (
          <div style={appStyles.areaRow}>
            <span style={appStyles.areaValue}>{convertArea(totalArea, areaUnit)}</span>
            <div style={appStyles.unitToggle}>
              {AREA_UNITS.map(u => (
                <button
                  key={u.id}
                  style={{ ...appStyles.unitBtn, ...(areaUnit === u.id ? appStyles.unitBtnActive : {}) }}
                  onClick={() => onAreaUnitChange(u.id)}
                >
                  {u.label}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>메모</div>
        <textarea
          value={draft.memo}
          onChange={(e) => setDraft(d => ({ ...d, memo: e.target.value }))}
          placeholder="그룹에 대한 메모를 입력하세요"
          style={appStyles.memoInput}
          rows={2}
        />
      </div>

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>표시 방식</div>
        <div style={appStyles.styleRow}>
          {STYLE_OPTIONS.map(s => {
            const active = draft.style === s.id;
            const disabled = !draft.color;
            return (
              <button
                key={s.id}
                disabled={disabled}
                style={{
                  ...appStyles.styleBtn,
                  ...(active ? appStyles.styleBtnActive : {}),
                  ...(disabled ? appStyles.styleBtnDisabled : {}),
                }}
                onClick={() => setDraft(d => ({ ...d, style: s.id }))}
              >
                <StylePreview style={s.id} color={(draft.color && colorMap[draft.color]) ? colorMap[draft.color].hex : '#C9C4B6'} active={active}/>
                <span style={appStyles.styleLabel}>{s.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>색상</div>
        <div style={appStyles.swatchGrid}>
          <button
            style={{ ...appStyles.swatch, ...(draft.color == null ? appStyles.swatchActive : {}) }}
            onClick={() => setDraft(d => ({ ...d, color: null }))}
          >
            <div style={appStyles.swatchClear}>
              <i data-lucide="x" style={{ width: 16, height: 16, color: '#8E8B82' }}></i>
            </div>
            <span style={appStyles.swatchLabel}>없음</span>
          </button>
          {colorList.map(c => {
            const active = draft.color === c.id;
            return (
              <button
                key={c.id}
                style={{ ...appStyles.swatch, ...(active ? appStyles.swatchActive : {}) }}
                onClick={() => setDraft(d => ({ ...d, color: c.id }))}
              >
                <div style={{ ...appStyles.swatchChip, background: hexA(c.hex, 0.55), borderColor: c.hex }}></div>
                <span style={appStyles.swatchLabel}>{c.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>포함 필지 ({memberParcels.length})</div>
        <div style={appStyles.memberList}>
          {memberParcels.map(p => {
            const precise = areas[p.id]?.lndpcl_ar;
            const areaVal = precise ?? p.area ?? 0;
            return (
              <div key={p.id} style={appStyles.memberItem}>
                <span style={appStyles.memberJibun}>{p.jibun}</span>
                {areaVal > 0 && (
                  <span style={appStyles.memberArea}>{convertArea(areaVal, areaUnit)}</span>
                )}
                <button
                  style={appStyles.memberRemoveBtn}
                  onClick={() => onRemoveParcel(p.id)}
                  aria-label="제거"
                >
                  <i data-lucide="x" style={{ width: 14, height: 14 }}></i>
                </button>
              </div>
            );
          })}
        </div>
        {!isPending && (
          <button style={appStyles.memberAddBtn} onClick={() => { onClose(); onAddParcels(); }}>
            <i data-lucide="plus" style={{ width: 14, height: 14 }}></i>
            필지 추가
          </button>
        )}
      </div>

      <button style={appStyles.saveBtn} onClick={handleSave}>저장</button>
      <button style={appStyles.dissolveBtn} onClick={() => { onDissolve(); onClose(); }}>
        {isPending ? '취소' : '그룹 해체'}
      </button>
    </React.Fragment>
  );

  if (isWide) {
    return <div style={appStyles.sheetPanel}>{content}</div>;
  }

  return (
    <BottomSheet onClose={() => { if (Date.now() - openedAtRef.current > 500) onClose(); }}>
      {content}
    </BottomSheet>
  );
}
