// MyInfo — 내 정보 메인 + 시설 현황 설정

// ──────────────────────────────────────────────
// 공통 UI
// ──────────────────────────────────────────────
function InfoCard({ icon, title, subtitle, children, onEdit }) {
  return (
    <div style={{
      background: '#fff', border: '1px solid #ece9e0',
      borderRadius: 14, padding: '14px 16px', marginBottom: 12,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 12, gap: 8,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          {icon && <span style={{ fontSize: 16 }}>{icon}</span>}
          <div style={{ minWidth: 0 }}>
            <div style={{
              fontSize: 13, fontWeight: 800, color: '#1a1a18',
              letterSpacing: '-0.01em',
            }}>{title}</div>
            {subtitle && (
              <div style={{
                fontSize: 11, color: '#8a8880', fontWeight: 500, marginTop: 1,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>
                {subtitle}
              </div>
            )}
          </div>
        </div>
        {onEdit && (
          <button
            onClick={onEdit}
            style={{
              background: 'transparent', border: 'none', padding: 4,
              cursor: 'pointer', color: '#8a8880',
              display: 'inline-flex', alignItems: 'center',
              WebkitTapHighlightColor: 'transparent',
            }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M4 20h4l10-10a2.83 2.83 0 10-4-4L4 16v4z" stroke="#8a8880" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        )}
      </div>
      <div>{children}</div>
    </div>
  );
}

function InfoRow({ label, value, editable, onChange, placeholder }) {
  const [editing, setEditing] = React.useState(false);
  const [tempVal, setTempVal] = React.useState(value || '');
  const inputRef = React.useRef(null);

  React.useEffect(() => { setTempVal(value || ''); }, [value]);
  React.useEffect(() => { if (editing && inputRef.current) inputRef.current.focus(); }, [editing]);

  const commit = () => {
    setEditing(false);
    if (tempVal !== (value || '') && onChange) onChange(tempVal);
  };

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '90px 1fr auto',
      alignItems: 'center', gap: 10,
      padding: '9px 0',
      borderBottom: '1px solid #f5f3ec',
    }}>
      <span style={{ fontSize: 12, color: '#8a8880', fontWeight: 600 }}>
        {label}
      </span>
      {editing ? (
        <input
          ref={inputRef}
          type="text"
          value={tempVal}
          onChange={e => setTempVal(e.target.value)}
          onBlur={commit}
          onKeyDown={e => { if (e.key === 'Enter') commit(); }}
          placeholder={placeholder || ''}
          style={{
            fontSize: 13, fontWeight: 500, color: '#1a1a18',
            border: '1px solid #d4d1c7', borderRadius: 6,
            padding: '4px 8px', outline: 'none', fontFamily: 'inherit',
            background: '#fbf9f3', width: '100%', boxSizing: 'border-box',
          }}
        />
      ) : (
        <span style={{
          fontSize: 13, color: value ? '#1a1a18' : '#b8b4a8',
          fontWeight: 500, wordBreak: 'keep-all',
        }}>
          {value || '—'}
        </span>
      )}
      {editable && !editing && (
        <button onClick={() => setEditing(true)} style={{
          background: 'transparent', border: 'none', padding: 4,
          cursor: 'pointer', WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
            <path d="M4 20h4l10-10a2.83 2.83 0 10-4-4L4 16v4z" stroke="#b8b4a8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      )}
      {editable && editing && (
        <span style={{ fontSize: 11, color: '#8a8880', fontWeight: 500 }}>완료↵</span>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────
// 비밀번호 변경 섹션
// ──────────────────────────────────────────────
function PasswordSection({ onSave }) {
  const [editing, setEditing] = React.useState(false);
  const [pw1, setPw1]         = React.useState('');
  const [pw2, setPw2]         = React.useState('');
  const [err, setErr]         = React.useState('');
  const [saving, setSaving]   = React.useState(false);
  const pw1Ref = React.useRef(null);

  React.useEffect(() => {
    if (editing && pw1Ref.current) pw1Ref.current.focus();
  }, [editing]);

  const cancel = () => {
    setEditing(false);
    setPw1(''); setPw2(''); setErr('');
  };

  const commit = async () => {
    if (!pw1)          { setErr('새 비밀번호를 입력하세요.'); return; }
    if (pw1.length < 4){ setErr('비밀번호는 4자 이상이어야 합니다.'); return; }
    if (pw1 !== pw2)   { setErr('비밀번호가 일치하지 않습니다.'); return; }
    setSaving(true);
    try {
      await onSave(pw1);
      cancel();
    } catch (e) {
      setErr(e.message || '저장 실패');
    } finally {
      setSaving(false);
    }
  };

  const rowBase = {
    display: 'grid', gridTemplateColumns: '90px 1fr auto',
    alignItems: 'center', gap: 10,
    padding: '9px 0', borderBottom: '1px solid #f5f3ec',
  };
  const inputSt = {
    width: '100%', height: 38, padding: '0 10px',
    border: '1px solid #d4d1c7', borderRadius: 6,
    fontSize: 13, fontFamily: 'inherit', outline: 'none',
    background: '#fbf9f3', color: '#1a1a18',
    boxSizing: 'border-box',
  };
  const pencilSvg = (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
      <path d="M4 20h4l10-10a2.83 2.83 0 10-4-4L4 16v4z"
        stroke="#b8b4a8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );

  if (!editing) {
    return (
      <div style={rowBase}>
        <span style={{ fontSize: 12, color: '#8a8880', fontWeight: 600 }}>비밀번호</span>
        <span style={{ fontSize: 13, color: '#b8b4a8', fontWeight: 500, letterSpacing: '0.1em' }}>
          ••••••••
        </span>
        <button onClick={() => setEditing(true)} style={{
          background: 'transparent', border: 'none', padding: 4,
          cursor: 'pointer', WebkitTapHighlightColor: 'transparent',
        }}>
          {pencilSvg}
        </button>
      </div>
    );
  }

  return (
    <div style={{ padding: '10px 0', borderBottom: '1px solid #f5f3ec' }}>
      <div style={{ fontSize: 12, color: '#8a8880', fontWeight: 600, marginBottom: 8 }}>
        비밀번호 변경
      </div>
      <div style={{ display: 'grid', gap: 6, marginBottom: 8 }}>
        <input
          ref={pw1Ref}
          type="password"
          placeholder="새 비밀번호 (4자 이상)"
          value={pw1}
          onChange={e => { setPw1(e.target.value); setErr(''); }}
          style={inputSt}
        />
        <input
          type="password"
          placeholder="새 비밀번호 확인"
          value={pw2}
          onChange={e => { setPw2(e.target.value); setErr(''); }}
          onKeyDown={e => e.key === 'Enter' && commit()}
          style={inputSt}
        />
      </div>
      {err && (
        <div style={{
          fontSize: 11.5, color: '#cc2222', fontWeight: 600,
          marginBottom: 8, lineHeight: 1.4,
        }}>
          {err}
        </div>
      )}
      <div style={{ display: 'flex', gap: 6 }}>
        <button onClick={cancel} style={{
          flex: 1, height: 34, border: '1px solid #d4d1c7', borderRadius: 8,
          background: '#fff', color: '#5a5a55', fontSize: 12.5, fontWeight: 700,
          fontFamily: 'inherit', cursor: 'pointer',
          WebkitTapHighlightColor: 'transparent',
        }}>
          취소
        </button>
        <button onClick={commit} disabled={saving} style={{
          flex: 2, height: 34, border: 'none', borderRadius: 8,
          background: saving ? '#9db4ea' : '#2563EB',
          color: '#fff', fontSize: 12.5, fontWeight: 700,
          fontFamily: 'inherit', cursor: saving ? 'wait' : 'pointer',
          WebkitTapHighlightColor: 'transparent',
          transition: 'background 200ms',
        }}>
          {saving ? '저장 중…' : '완료'}
        </button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────
// 내 정보 메인
// ──────────────────────────────────────────────
function MyInfoScreen({ building, account, onAccountChange, facilities, onOpenFacilities, onLogout, theme }) {
  const t = theme || THEME;

  // DB 저장 래퍼: state 즉시 업데이트 + API 호출
  const saveAccount = (updated) => {
    const token = localStorage.getItem('soritalk:token') || localStorage.getItem('token');
    onAccountChange(updated);
    fetch('/api/auth/account', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      credentials: 'include',
      body: JSON.stringify(updated)
    })
    .then(r => r.json())
    .then(d => {
      if (!d.success) { alert('저장 실패: ' + (d.error || '')); return; }
      if (d.account) onAccountChange({ ...updated, ...d.account });
    })
    .catch(e => alert('저장 오류: ' + e.message));
  };

  const savePassword = async (newPassword) => {
    const token = localStorage.getItem('soritalk:token') || localStorage.getItem('token');
    const res = await fetch('/api/auth/account', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      credentials: 'include',
      body: JSON.stringify({ newPassword }),
    });
    const d = await res.json();
    if (!d.success) throw new Error(d.error || '비밀번호 저장 실패');
  };

  const facilityCount = Object.values(facilities).filter(v => v === 'yes' || v === 'manual').length;

  // API 데이터 또는 Mock 데이터 매핑
  const bldg = building || window.BUILDING || {};
  const bTradeName = bldg.trade_name || bldg.tradeName || '';
  const bName = bldg.name || bldg.building || '';
  const bAddress = bldg.address || '';
  const bGrade = bldg.grade || '';
  const bFloorsAbove = bldg.floors_above || bldg.floorsAbove || 0;
  const bFloorsBelow = bldg.floors_below || bldg.floorsBelow || 0;
  const bAreaSqm = bldg.area_sqm || bldg.areaSqm || 0;
  const bFloorSqm = bldg.floor_sqm || bldg.floorSqm || 0;
  const bCount = parseInt(bldg.buildings_count || bldg.buildingsCount) || 0;
  
  const mName = bldg.manager_name || bldg.managerName || '';
  const mPos = bldg.manager_position || bldg.managerPosition || '';
  const mGrade = bldg.manager_grade || bldg.managerGrade || '';
  const mPhone = bldg.manager_phone || bldg.managerPhone || '';
  const fmName = bldg.fire_manager_name || bldg.fireManagerName || '';
  const fmPhone = bldg.fire_manager_phone || bldg.fireManagerPhone || '';

  return (
    <div style={{ padding: '14px 16px 24px' }}>
      {/* 프로필 헤더 */}
      <div style={{
        background: 'linear-gradient(135deg, #fff 0%, #fbf9f3 100%)',
        border: '1px solid #ece9e0',
        borderRadius: 16, padding: '18px 16px', marginBottom: 14,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%',
          background: `linear-gradient(135deg, ${t.brand}, ${t.brand}cc)`,
          color: '#fff', fontWeight: 800, fontSize: 22,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0, letterSpacing: '-0.02em',
          boxShadow: `0 4px 12px ${t.brand}44`,
        }}>
          {(account.name || 'U').slice(0, 1)}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 800, color: '#1a1a18', letterSpacing: '-0.02em' }}>
            {account.name}
          </div>
          <div style={{ fontSize: 12, color: '#8a8880', fontWeight: 600, marginTop: 2 }}>
            {account.loginId} · {account.phone}
          </div>
        </div>
      </div>

      {/* 섹션 1 — 건물 기본 정보 */}
      <InfoCard icon="🏢" title="건물 기본 정보" subtitle="관리자만 수정 가능">
        <InfoRow label="상호명" value={bTradeName} />
        <InfoRow label="건물명" value={bName} />
        <InfoRow label="주소" value={bAddress} />
        <InfoRow label="건물 용도" value={bGrade} />
        <InfoRow label="층수" value={`지상 ${bFloorsAbove}층 / 지하 ${bFloorsBelow}층`} />
        <InfoRow label="연면적" value={bAreaSqm ? `${bAreaSqm}㎡` : ''} />
        <InfoRow label="층별 면적" value={bFloorSqm ? `${bFloorSqm}㎡` : ''} />
        <InfoRow label="건물 수" value={bCount ? `${bCount}동` : ''} />
        <div style={{ height: 1 }} />
      </InfoCard>

      {/* 섹션 2 — 소방안전관리자 */}
      <InfoCard icon="🧑‍🚒" title="소방안전관리자" subtitle="관리자만 수정 가능">
        <InfoRow label="관리자명" value={fmName} />
        {/* 직위·자격 등급 — 현재 미사용, 나중을 위해 데이터는 유지하되 표시 숨김 */}
        {/* <InfoRow label="직위" value={mPos} /> */}
        {/* <InfoRow label="자격 등급" value={mGrade} /> */}
        <InfoRow label="연락처" value={fmPhone} />
        <div style={{ height: 1 }} />
      </InfoCard>

      {/* 섹션 3 — 내 계정 정보 */}
      <InfoCard icon="👤" title="내 계정 정보" subtitle="연락처·SMS 수정 가능">
        <InfoRow label="이름" value={account.name || ''}
          editable onChange={v => saveAccount({ ...account, name: v })}
          placeholder="이름 입력" />
        <InfoRow label="아이디" value={account.loginId || account.username || ''} />
        <InfoRow label="연락처" value={account.phone || ''}
          editable onChange={v => saveAccount({ ...account, phone: v })}
          placeholder="010-0000-0000" />
        <InfoRow label="카드번호" value={account.cardNo || account.card_no || ''} />
        <InfoRow label="SMS 수신1" value={account.smsExtra1 || ''}
          editable onChange={v => saveAccount({ ...account, smsExtra1: v })}
          placeholder="010-0000-0000" />
        <PasswordSection onSave={savePassword} />
        <div style={{ height: 1 }} />
      </InfoCard>

      {/* 섹션 4 — 시설 현황 진입 버튼 */}
      <button
        onClick={onOpenFacilities}
        style={{
          width: '100%', background: '#fff',
          border: '1px solid #ece9e0', borderRadius: 14,
          padding: '14px 16px', marginBottom: 14,
          display: 'flex', alignItems: 'center', gap: 12,
          cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
          WebkitTapHighlightColor: 'transparent',
        }}
      >
        <span style={{ fontSize: 18 }}>🏗️</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 800, color: '#1a1a18', letterSpacing: '-0.01em' }}>
            우리 건물 시설 현황
          </div>
          <div style={{ fontSize: 11.5, color: '#8a8880', fontWeight: 500, marginTop: 2 }}>
            {facilityCount}/{FACILITY_ITEMS.length}개 시설 설치 · 설정 수정
          </div>
        </div>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
          <path d="M9 6l6 6-6 6" stroke="#b8b4a8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>

      {/* 로그아웃 */}
      <button
        onClick={onLogout}
        style={{
          width: '100%', background: '#fff',
          border: '1px solid #f4cccc', borderRadius: 12,
          padding: '13px', color: '#cc2222',
          fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
          cursor: 'pointer', WebkitTapHighlightColor: 'transparent',
        }}
      >
        로그아웃
      </button>
    </div>
  );
}

// ──────────────────────────────────────────────
// 시설 현황 설정
// ──────────────────────────────────────────────
function FacilitySettingsScreen({ facilities, onChange, onSave, theme }) {
  const t = theme || THEME;
  const [local, setLocal] = React.useState(facilities);
  const dirty = React.useMemo(
    () => JSON.stringify(local) !== JSON.stringify(facilities),
    [local, facilities]
  );

  const setVal = (id, v) => setLocal(prev => ({ ...prev, [id]: v }));
  const counts = {
    yes: Object.values(local).filter(v => v === 'yes').length,
    no: Object.values(local).filter(v => v === 'no').length,
    manual: Object.values(local).filter(v => v === 'manual').length,
  };

  return (
    <div style={{ padding: '14px 16px 24px' }}>
      {/* 요약 헤더 */}
      <div style={{
        background: '#fff', border: '1px solid #ece9e0',
        borderRadius: 14, padding: '14px 16px', marginBottom: 14,
      }}>
        <div style={{
          fontSize: 13, fontWeight: 800, color: '#1a1a18',
          letterSpacing: '-0.01em', marginBottom: 10,
        }}>
          시설 현황 요약
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
          <SummaryPill color="#15803d" bg="#e9f6ee" label="있음" n={counts.yes} />
          <SummaryPill color="#2563eb" bg="#eaf2ff" label="직접입력" n={counts.manual} />
          <SummaryPill color="#8a8880" bg="#f1efea" label="없음" n={counts.no} />
        </div>
        <div style={{
          fontSize: 11.5, color: '#8a8880', fontWeight: 500,
          marginTop: 10, lineHeight: 1.5,
        }}>
          '없음' 선택 시 점검 화면에서 해당 설비군이 숨겨집니다.
          '직접입력'은 이상없음 / 직접입력 2버튼으로 기록합니다.
        </div>
      </div>

      {/* 14개 항목 리스트 */}
      <div style={{
        background: '#fff', border: '1px solid #ece9e0',
        borderRadius: 14, padding: '6px 0', marginBottom: 14,
      }}>
        {FACILITY_ITEMS.map((f, i) => {
          const val = local[f.id] || 'no';
          return (
            <FacilityRow
              key={f.id}
              index={i + 1}
              item={f}
              value={val}
              onChange={v => setVal(f.id, v)}
              isLast={i === FACILITY_ITEMS.length - 1}
            />
          );
        })}
      </div>

      {/* 저장 버튼 */}
      <button
        disabled={!dirty}
        onClick={() => { onChange(local); onSave && onSave(local); }}
        style={{
          width: '100%', height: 50,
          background: dirty ? t.brand : '#e5e3dc',
          color: '#fff', border: 'none', borderRadius: 12,
          fontSize: 14, fontWeight: 800, fontFamily: 'inherit',
          letterSpacing: '-0.01em',
          cursor: dirty ? 'pointer' : 'not-allowed',
          boxShadow: dirty ? `0 4px 12px ${t.brand}55` : 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          transition: 'background 260ms, box-shadow 260ms',
          WebkitTapHighlightColor: 'transparent',
        }}
      >
        저장
        {dirty && (
          <span style={{
            fontSize: 11, fontWeight: 700,
            background: 'rgba(255,255,255,.25)',
            padding: '2px 6px', borderRadius: 6,
          }}>
            변경됨
          </span>
        )}
      </button>
    </div>
  );
}

function SummaryPill({ color, bg, label, n }) {
  return (
    <div style={{
      background: bg, borderRadius: 10, padding: '9px 8px',
      textAlign: 'center',
    }}>
      <div style={{
        fontSize: 18, fontWeight: 800, color,
        letterSpacing: '-0.02em', lineHeight: 1,
      }}>{n}</div>
      <div style={{
        fontSize: 10.5, color, fontWeight: 700,
        marginTop: 4,
      }}>{label}</div>
    </div>
  );
}

function FacilityRow({ index, item, value, onChange, isLast }) {
  const dim = value === 'no';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '11px 14px',
      borderBottom: isLast ? 'none' : '1px solid #f5f3ec',
      opacity: dim ? 0.55 : 1,
      transition: 'opacity 220ms',
    }}>
      <span style={{
        width: 22, flexShrink: 0,
        fontSize: 11, color: '#b8b4a8', fontWeight: 700,
        textAlign: 'right',
      }}>
        {String(index).padStart(2, '0')}
      </span>
      <div style={{
        flex: 1, minWidth: 0,
        fontSize: 12.5, fontWeight: 600,
        color: dim ? '#8a8880' : '#1a1a18',
        lineHeight: 1.35,
        textDecoration: dim ? 'line-through' : 'none',
      }}>
        {item.label}
      </div>
      <TriSegment value={value} onChange={onChange} />
    </div>
  );
}

function TriSegment({ value, onChange }) {
  const opts = [
    { v: 'yes',    label: '있음',   fg: '#15803d', bg: '#e9f6ee', border: '#bfe1ca' },
    { v: 'manual', label: '직접',   fg: '#2563eb', bg: '#eaf2ff', border: '#b8ccf0' },
    { v: 'no',     label: '없음',   fg: '#8a8880', bg: '#f1efea', border: '#d4d1c7' },
  ];
  return (
    <div style={{
      display: 'flex',
      background: '#fbf9f3', borderRadius: 8,
      padding: 2, border: '1px solid #ece9e0',
      flexShrink: 0,
    }}>
      {opts.map(o => {
        const active = value === o.v;
        return (
          <button
            key={o.v}
            onClick={() => onChange(o.v)}
            style={{
              border: 'none', background: active ? '#fff' : 'transparent',
              color: active ? o.fg : '#8a8880',
              fontWeight: active ? 800 : 600,
              fontSize: 11, fontFamily: 'inherit',
              padding: '6px 9px', borderRadius: 6,
              cursor: 'pointer',
              boxShadow: active ? `0 1px 3px rgba(0,0,0,.08), inset 0 0 0 1px ${o.border}` : 'none',
              transition: 'all 180ms',
              WebkitTapHighlightColor: 'transparent',
              whiteSpace: 'nowrap',
            }}
          >
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

window.MyInfoScreen = MyInfoScreen;
window.FacilitySettingsScreen = FacilitySettingsScreen;
