/* ───────── YouTube Section — feature + side list ───────── */

const YT_CHANNEL = {
  name: '사업자 필독',
  handle: '@사업자필독',
  url: 'https://www.youtube.com/@%EC%82%AC%EC%97%85%EC%9E%90%ED%95%84%EB%8F%85',
  subs: '구독자',
  tagline: '소상공인 · 중소기업 사장님을 위한 자금 인사이트',
  avatar: '사필',
};

const YT_RENTAL_CHANNEL = {
  name: '렌탈박스',
  handle: '@Rantalbox_official',
  url: 'https://www.youtube.com/@Rantalbox_official',
  subs: '구독자',
  tagline: '제조·중소기업·창업자를 위한 장비 렌탈 가이드',
  avatar: '렌탈',
};

const YT_VIDEOS = [
  { id: 'Pyd66uWKNx8', ep: 'EP.01', title: '정책자금, 어디서부터 시작해야 할까',     tag: '입문' },
  { id: 'Oycgp8qlvmM', ep: 'EP.02', title: '컨설팅 업체 고르는법',     tag: '비교' },
  { id: '9zISMvDBg7g', ep: 'EP.03', title: '승인율을 높이는 서류 준비의 기본',       tag: '실무' },
  { id: 'mRaV8cPcpdc', ep: 'EP.04', title: '산업기계 렌탈로 예비비를 확보하는 법',   tag: '렌탈' },
];

const YT_RENTAL_VIDEOS = [
  { id: 'dd9DHhVqpnY', ep: 'EP.01', title: '제조 및 중소기업이 렌탈을 하는 이유?',           tag: '렌탈' },
  { id: 'yXDiRF2PNvY', ep: 'EP.02', title: '무상지원사업을 활용한 장비구매는 어떻게 해야할까?', tag: '무상지원' },
  { id: 'iUWrrl5Lpuw', ep: 'EP.03', title: '병원창업 시, 비싼 장비를 어떻게 구매해야 될까?',    tag: '병원' },
  { id: 'oPlXOuWQbIU', ep: 'EP.04', title: '무인편의점·카페 창업 시, 장비 구매 방법은?',         tag: '창업' },
];

const ytThumb = (id) => `https://img.youtube.com/vi/${id}/hqdefault.jpg`;
const ytWatch = (id) => `https://www.youtube.com/watch?v=${id}`;

function YoutubeSection({
  videos = YT_VIDEOS,
  channel = YT_CHANNEL,
  eyebrow = 'YouTube · 사업자 필독',
  headline = (<>자금 인사이트는,<br/>영상으로도 확인하세요.</>),
  intro = (<>운림 대표가 운영하는 <span className="font-semibold text-ink">『사업자 필독』</span> 채널에서<br/>정책자금·렌탈·인증의 실무 가이드를 한 편당 5분 안에 풀어드립니다.</>),
  bgClass = 'bg-white',
  showBorderTop = true,
} = {}) {
  const [active, setActive] = useState(0);
  const [playing, setPlaying] = useState(false); // user has clicked play
  const cur = videos[active];

  const handleSelect = (i) => {
    setActive(i);
    setPlaying(false); // show poster again for new video
  };

  return (
    <section className={`py-24 lg:py-32 ${bgClass} ${showBorderTop ? 'border-t border-line' : ''}`}>
      <div className="max-w-container mx-auto px-6 lg:px-8">
        <div className="flex items-end justify-between flex-wrap gap-6">
          <div className="max-w-[640px]">
            <div className="text-[13px] font-bold text-brand tracking-[.18em] uppercase">{eyebrow}</div>
            <h2 className="h-sec text-[32px] lg:text-[40px] text-ink mt-3">
              {headline}
            </h2>
            <p className="mt-5 text-[16px] lg:text-[17px] text-body body-lg">
              {intro}
            </p>
          </div>
          <a href={channel.url} target="_blank" rel="noopener"
             className="btn-ghost px-5 py-3 rounded-[12px] text-[14px] font-semibold hover:border-brand/40">
            채널 전체 보기 →
          </a>
        </div>

        <div className="mt-12 grid lg:grid-cols-[1.55fr_1fr] gap-6 lg:gap-8">
          {/* Feature player */}
          <div>
            <div className="relative aspect-video bg-ink rounded-big overflow-hidden border border-line">
              {playing ? (
                <iframe
                  key={cur.id}
                  className="absolute inset-0 w-full h-full"
                  src={`https://www.youtube-nocookie.com/embed/${cur.id}?autoplay=1&rel=0&modestbranding=1&playsinline=1`}
                  title={cur.title}
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowFullScreen
                  referrerPolicy="strict-origin-when-cross-origin"
                />
              ) : (
                <button type="button" onClick={() => setPlaying(true)}
                  className="absolute inset-0 group block">
                  <img src={ytThumb(cur.id)} alt={cur.title}
                       className="absolute inset-0 w-full h-full object-cover" />
                  <div className="absolute inset-0"
                       style={{background:'linear-gradient(180deg, rgba(11,31,58,0.0) 35%, rgba(11,31,58,0.7) 100%)'}} />
                  <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2
                                   w-[78px] h-[78px] rounded-full bg-white/95 group-hover:bg-white
                                   transition-all shadow-[0_10px_30px_rgba(11,31,58,0.35)]
                                   flex items-center justify-center">
                    <span className="block w-0 h-0
                                     border-y-[14px] border-y-transparent
                                     border-l-[22px] border-l-brand ml-2"></span>
                  </span>
                  <span className="absolute left-5 bottom-5 right-5 text-left text-white">
                    <span className="inline-block num text-[11px] font-bold tracking-[.18em] bg-white/15 backdrop-blur-md ring-1 ring-white/25 px-2 py-1 rounded-full">
                      {cur.ep} · {cur.tag}
                    </span>
                    <span className="block mt-3 text-[18px] lg:text-[22px] font-bold leading-tight max-w-[640px]">
                      {cur.title}
                    </span>
                  </span>
                </button>
              )}
            </div>

            {/* Always-available fallback: open on YouTube */}
            {playing && (
              <div className="mt-3 flex items-center justify-between gap-3">
                <p className="text-[12.5px] text-mute">
                  영상이 재생되지 않으면 YouTube에서 바로 확인할 수 있어요.
                </p>
                <a href={ytWatch(cur.id)} target="_blank" rel="noopener"
                   className="text-[13px] font-semibold text-brand hover:underline whitespace-nowrap">
                  YouTube에서 보기 ↗
                </a>
              </div>
            )}

            {/* Channel info row */}
            <div className="mt-5 flex items-center gap-4 p-4 lg:p-5 bg-soft rounded-card">
              <div className="w-12 h-12 rounded-full bg-ink text-white font-bold text-[13px] flex items-center justify-center flex-shrink-0">
                {channel.avatar}
              </div>
              <div className="min-w-0 flex-1">
                <div className="text-[15px] font-bold text-ink truncate">{channel.name}</div>
                <div className="text-[13px] text-body truncate">{channel.tagline}</div>
              </div>
              <a href={channel.url} target="_blank" rel="noopener"
                 className="btn-brand px-4 py-2.5 rounded-[10px] text-[13px] font-semibold whitespace-nowrap">
                구독하기
              </a>
            </div>
          </div>

          {/* Side playlist */}
          <div className="bg-soft rounded-big border border-line p-4 lg:p-5">
            <div className="flex items-baseline justify-between px-1 mb-3">
              <div className="text-[13px] font-bold text-ink">추천 영상</div>
              <div className="num text-[12px] text-mute font-semibold">{videos.length}편</div>
            </div>
            <ul className="space-y-2">
              {videos.map((v, i) => {
                const on = active === i;
                return (
                  <li key={v.id}>
                    <button type="button" onClick={() => handleSelect(i)}
                      className={`group w-full text-left p-2 rounded-card transition-colors duration-200 flex gap-3 ${
                        on ? 'bg-white ring-1 ring-brand/30' : 'hover:bg-white'
                      }`}>
                      <div className="relative w-[120px] aspect-video rounded-[8px] overflow-hidden flex-shrink-0 bg-ink">
                        <img src={ytThumb(v.id)} alt="" className="absolute inset-0 w-full h-full object-cover" />
                        {on && (
                          <div className="absolute inset-0 flex items-center justify-center bg-brand/35">
                            <span className="w-7 h-7 rounded-full bg-white flex items-center justify-center">
                              <span className="block w-0 h-0
                                               border-y-[5px] border-y-transparent
                                               border-l-[8px] border-l-brand ml-[2px]"></span>
                            </span>
                          </div>
                        )}
                      </div>
                      <div className="min-w-0 flex-1 py-0.5">
                        <div className={`num text-[11px] font-bold tracking-[.12em] ${on ? 'text-brand' : 'text-mute'}`}>
                          {v.ep} · {v.tag}
                        </div>
                        <div className={`mt-1 text-[13.5px] font-semibold leading-snug line-clamp-2 ${on ? 'text-ink' : 'text-ink group-hover:text-ink'}`}>
                          {v.title}
                        </div>
                      </div>
                    </button>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { YoutubeSection, YT_VIDEOS, YT_RENTAL_VIDEOS, YT_CHANNEL, YT_RENTAL_CHANNEL });
