/* Admin — upload / new content form */

function emptyWeeklyPlan() {
  return Array.from({ length: 4 }, () => ({
    activities: [
      { badge: '교사용 PDF', title: '', sub: '' },
      { badge: '활동지', title: '', sub: '' },
    ],
    chapters: [
      { no: '1', title: '', sub: '', time: '15분' },
      { no: '2', title: '', sub: '', time: '15분' },
      { no: '+', title: '', sub: '', time: '10분' },
    ],
  }));
}

function WeeklyPlanEditor({ plan, setPlan }) {
  const [wk, setWk] = React.useState(0);
  const week = plan[wk];

  const updateActivity = (i, field, value) => {
    setPlan((prev) => prev.map((w, wi) => (wi !== wk ? w : {
      ...w, activities: w.activities.map((a, ai) => (ai !== i ? a : { ...a, [field]: value })),
    })));
  };
  const updateChapter = (i, field, value) => {
    setPlan((prev) => prev.map((w, wi) => (wi !== wk ? w : {
      ...w, chapters: w.chapters.map((c, ci) => (ci !== i ? c : { ...c, [field]: value })),
    })));
  };

  return (
    <div className="admin-panel">
      <div className="admin-panel-head">
        <h3>주차별 커리큘럼</h3>
        <span className="hint">비워두면 해당 주차는 사이트에 노출되지 않아요</span>
      </div>
      <div className="pill-select" style={{ marginBottom: 20 }}>
        {plan.map((w, i) => (
          <button key={i} type="button" className={wk === i ? 'active' : ''} onClick={() => setWk(i)}>{i + 1}주차</button>
        ))}
      </div>

      <div className="admin-nav-label" style={{ marginBottom: 10 }}>교사 활동지도</div>
      {week.activities.map((a, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 1fr', gap: 10, marginBottom: 10 }}>
          <input className="admin-input" style={{ width: '100%' }} type="text" value={a.badge}
                 placeholder="뱃지" onChange={(e) => updateActivity(i, 'badge', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={a.title}
                 placeholder={(i === 0 ? '모모' : '테리') + ' 활동 제목'} onChange={(e) => updateActivity(i, 'title', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={a.sub}
                 placeholder="설명" onChange={(e) => updateActivity(i, 'sub', e.target.value)} />
        </div>
      ))}

      <div className="admin-nav-label" style={{ margin: '22px 0 10px' }}>수업 흐름 (차시)</div>
      {week.chapters.map((c, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 90px', gap: 10, marginBottom: 10 }}>
          <input className="admin-input" style={{ width: '100%' }} type="text" value={c.title}
                 placeholder={'차시 ' + c.no + ' 제목'} onChange={(e) => updateChapter(i, 'title', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={c.sub}
                 placeholder="설명" onChange={(e) => updateChapter(i, 'sub', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={c.time}
                 placeholder="시간" onChange={(e) => updateChapter(i, 'time', e.target.value)} />
        </div>
      ))}
    </div>
  );
}

function emptyFamilyItems() {
  return [
    { label: '📚 동화책과 책놀이', title: '', kind: '그림책', vol: '전 6P', sub: '' },
    { label: '🎵 노래배우기 + 율동', title: '', kind: '율동영상', vol: '전 6P', sub: '' },
    { label: '🎧 주간 오디오', title: '', kind: '듣기자료', vol: '전 6P', sub: '' },
  ];
}

function emptyVideos() {
  return [
    { title: '', tag: '', sub: '' },
    { title: '', tag: '', sub: '' },
    { title: '', tag: '', sub: '' },
  ];
}

function FamilyExtrasEditor({ familyItems, setFamilyItems, videos, setVideos }) {
  const updateFamily = (i, field, value) => setFamilyItems((prev) => prev.map((f, fi) => (fi !== i ? f : { ...f, [field]: value })));
  const updateVideo = (i, field, value) => setVideos((prev) => prev.map((v, vi) => (vi !== i ? v : { ...v, [field]: value })));

  return (
    <div className="admin-panel">
      <div className="admin-panel-head">
        <h3>확장수업 (가정 연계) 자료</h3>
        <span className="hint">비워두면 확장수업 페이지에 노출되지 않아요</span>
      </div>

      <div className="admin-nav-label" style={{ marginBottom: 10 }}>가정 연계 카드 3종</div>
      {familyItems.map((f, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '110px 1fr 1fr 90px', gap: 10, marginBottom: 10, alignItems: 'center' }}>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--muted)' }}>{f.kind}</span>
          <input className="admin-input" style={{ width: '100%' }} type="text" value={f.title}
                 placeholder="제목 (줄바꿈은 \n으로)" onChange={(e) => updateFamily(i, 'title', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={f.sub}
                 placeholder="설명" onChange={(e) => updateFamily(i, 'sub', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={f.vol}
                 placeholder="분량" onChange={(e) => updateFamily(i, 'vol', e.target.value)} />
        </div>
      ))}

      <div className="admin-nav-label" style={{ margin: '22px 0 10px' }}>추천 영상 3개</div>
      {videos.map((v, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 130px 1fr', gap: 10, marginBottom: 10 }}>
          <input className="admin-input" style={{ width: '100%' }} type="text" value={v.title}
                 placeholder={'영상 ' + (i + 1) + ' 제목'} onChange={(e) => updateVideo(i, 'title', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={v.tag}
                 placeholder="태그" onChange={(e) => updateVideo(i, 'tag', e.target.value)} />
          <input className="admin-input" style={{ width: '100%' }} type="text" value={v.sub}
                 placeholder="설명 · 시간" onChange={(e) => updateVideo(i, 'sub', e.target.value)} />
        </div>
      ))}
    </div>
  );
}

function emptyDownloads() {
  return DOWNLOAD_KINDS.map((k) => ({ kind: k, file_url: '', file_label: '' }));
}

function DownloadsEditor({ downloads, setDownloads }) {
  return (
    <div className="admin-panel">
      <div className="admin-panel-head">
        <h3>다운로드 자료 4종</h3>
        <span className="hint">URL을 비워두면 사이트에서 해당 항목이 비활성화돼요</span>
      </div>
      <DownloadsFieldsEditor downloads={downloads} setDownloads={setDownloads} />
    </div>
  );
}

function UploadScreen({ go }) {
  const [type, setType] = React.useState('수업지원자료');
  const STEPS = Array.from({ length: 12 }, (_, i) => (i + 1) + '호');
  const [step, setStep] = React.useState('1호');
  const [track, setTrack] = React.useState('모모');
  const [topic, setTopic] = React.useState('첫 인사');
  const [title, setTitle] = React.useState('인사로 여는 하루');
  const [description, setDescription] = React.useState('모모랑 테리랑 함께 배우는 오늘의 주제예요.');
  const [videoUrl, setVideoUrl] = React.useState('https://player.vimeo.com/video/1208672189?h=d3ac087858');
  const [goals, setGoals] = React.useState(['고운 말로 인사하며 하루를 시작할 수 있다.']);
  const [weeklyPlan, setWeeklyPlan] = React.useState(emptyWeeklyPlan);
  const [familyItems, setFamilyItems] = React.useState(emptyFamilyItems);
  const [videos, setVideos] = React.useState(emptyVideos);
  const [downloads, setDownloads] = React.useState(emptyDownloads);
  const [publishNow, setPublishNow] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(false);

  const setGoal = (i, v) => setGoals((gs) => gs.map((g, idx) => (idx === i ? v : g)));
  const addGoal = () => setGoals((gs) => [...gs, '']);
  const removeGoal = (i) => setGoals((gs) => gs.filter((_, idx) => idx !== i));

  const save = async () => {
    setSaving(true);
    const row = await insertContent({
      title,
      type,
      step: type === '수업지원자료' ? step : null,
      track: type === '수업지원자료' ? track : null,
      topic,
      description,
      video_url: videoUrl,
      goals: goals.filter((g) => g.trim() !== ''),
      status: publishNow ? 'published' : 'draft',
      pastel: Math.floor(Math.random() * 6),
    });
    if (row && type === '수업지원자료') {
      await insertWeeklyPlan(row.id, weeklyPlan);
      await insertFamilyExtras(row.id, familyItems, videos);
      await saveContentDownloads(row.id, downloads);
    }
    setSaving(false);
    if (row) {
      setSaved(true);
      setTimeout(() => go(type === '수업지원자료' ? 'materials' : 'family'), 900);
    }
  };

  return (
    <div>
      <div className="admin-topbar">
        <div><h1>새 콘텐츠 등록</h1><p>수업지원자료 또는 확장수업 콘텐츠를 등록합니다.</p></div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" onClick={() => go('dashboard')}>취소</button>
          <button className="btn btn-primary" disabled={saving} onClick={save}>{saving ? '저장 중…' : '저장하기'}</button>
        </div>
      </div>

      {saved && (
        <div className="admin-panel" style={{ background: 'var(--primary-tint)', color: 'var(--primary-strong)', fontWeight: 800, textAlign: 'center' }}>
          ✅ 콘텐츠가 저장되었습니다.
        </div>
      )}

      <div className="admin-form-grid">
        {/* left: media */}
        <div>
          <div className="admin-panel">
            <div className="form-field">
              <label>대표 이미지</label>
              <Ph label="썸네일 이미지를 올려주세요" className="upload-thumb-slot" />
            </div>
            <div className="form-field" style={{ marginBottom: 0 }}>
              <label>첨부 파일 <span className="hint">지도서 · 활동지 PDF</span></label>
              <div style={{ border: '1.5px dashed var(--line)', borderRadius: 12, padding: '22px 14px', textAlign: 'center', color: 'var(--muted)', fontSize: 13.5, fontWeight: 700 }}>
                파일을 여기로 드래그하거나 클릭해 업로드
              </div>
            </div>
          </div>
        </div>

        {/* right: fields */}
        <div className="admin-panel">
          <div className="form-field">
            <label>콘텐츠 구분</label>
            <div className="pill-select">
              {['수업지원자료', '확장수업'].map((t) => (
                <button key={t} type="button" className={type === t ? 'active' : ''} onClick={() => setType(t)}>{t}</button>
              ))}
            </div>
          </div>

          <div className="form-field">
            <label>제목</label>
            <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
          </div>

          <div className="form-field">
            <label>주제</label>
            <select value={topic} onChange={(e) => setTopic(e.target.value)}>
              {TOPICS.map((t) => (<option key={t}>{t}</option>))}
            </select>
          </div>

          {type === '수업지원자료' && (
            <div className="form-field">
              <label>단계</label>
              <select value={step} onChange={(e) => setStep(e.target.value)}>
                {STEPS.map((s) => (<option key={s}>{s}</option>))}
              </select>
            </div>
          )}

          {type === '수업지원자료' && (
            <div className="form-field">
              <label>구분 <span className="hint">사이트에서 캐릭터별로 나뉘어 노출돼요</span></label>
              <div className="pill-select">
                <button type="button" className={track === '모모' ? 'active' : ''} onClick={() => setTrack('모모')}>STEP1 (모모)</button>
                <button type="button" className={track === '테리' ? 'active' : ''} onClick={() => setTrack('테리')}>STEP2 (테리)</button>
              </div>
            </div>
          )}

          <div className="form-field">
            <label>소개 문구</label>
            <textarea value={description} onChange={(e) => setDescription(e.target.value)}></textarea>
          </div>

          <div className="form-field">
            <label>영상 URL <span className="hint">Vimeo 링크 (미리보기 5초 자동재생에 사용)</span></label>
            <input type="text" placeholder="https://player.vimeo.com/video/1208672189?h=d3ac087858" value={videoUrl} onChange={(e) => setVideoUrl(e.target.value)} />
          </div>

          <div className="form-field">
            <label>학습 목표 <span className="hint">최대 6개</span></label>
            {goals.map((g, i) => (
              <div className="goal-input-row" key={i}>
                <input type="text" value={g} onChange={(e) => setGoal(i, e.target.value)} placeholder="학습 목표를 입력하세요" />
                <button type="button" onClick={() => removeGoal(i)}><Ico d={ICONS.trash} size={15}/></button>
              </div>
            ))}
            <button type="button" className="chip" onClick={addGoal}>+ 목표 추가</button>
          </div>

          <div className="form-field" style={{ marginBottom: 0 }}>
            <label>공개 상태</label>
            <div className="pill-select">
              <button type="button" className={!publishNow ? 'active' : ''} onClick={() => setPublishNow(false)}>임시저장</button>
              <button type="button" className={publishNow ? 'active' : ''} onClick={() => setPublishNow(true)}>즉시 공개</button>
            </div>
          </div>
        </div>
      </div>

      {type === '수업지원자료' && (
        <React.Fragment>
          <WeeklyPlanEditor plan={weeklyPlan} setPlan={setWeeklyPlan} />
          <DownloadsEditor downloads={downloads} setDownloads={setDownloads} />
          <FamilyExtrasEditor familyItems={familyItems} setFamilyItems={setFamilyItems} videos={videos} setVideos={setVideos} />
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { UploadScreen });
