import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './_shell/tokens.css';
import './_shell/shell.css';
import useViewportMode from './_shell/useViewportMode';
import BottomNav from './_shell/BottomNav';
import DesktopHeader from './_shell/DesktopHeader';
import MatchMobile from './views/match.mobile.jsx';
import MatchDesktop from './views/match.desktop.jsx';
import { compatInterpret } from '../../api';

const EMPTY_PERSON = {
  name: '', year: '', month: '', day: '', hour: null,
  gender: 'male', calendar_type: 'solar',
};

export default function Compatibility() {
  const mode = useViewportMode();
  const navigate = useNavigate();
  const [personA, setPersonA] = useState({ ...EMPTY_PERSON });
  const [personB, setPersonB] = useState({ ...EMPTY_PERSON });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    setError(null);
    if (!personA.year || !personA.month || !personA.day ||
        !personB.year || !personB.month || !personB.day) {
      setError('두 사람의 생년월일을 입력해주세요.');
      return;
    }
    setLoading(true);
    try {
      const res = await compatInterpret({ person_a: personA, person_b: personB });
      navigate(`/saju/compatibility/result?cid=${res.reading_id}`);
    } catch (err) {
      setError(err?.message || '궁합 풀이에 실패했어요.');
    } finally {
      setLoading(false);
    }
  };

  const props = {
    personA, personB, onChangeA: setPersonA, onChangeB: setPersonB,
    onSubmit: handleSubmit, loading, error,
  };
  return (
    <div className="saju-v2">
      {mode === 'desktop' && <DesktopHeader />}
      {mode === 'desktop' ? <MatchDesktop {...props} /> : <MatchMobile {...props} />}
      {mode === 'mobile' && <BottomNav theme="ivory" />}
    </div>
  );
}
