// hifi-sections.jsx — all page sections for the corporate site
// Composed in HiFiApp via window.* exports.

// ───────────────────────────────────────────────────────────
// useReveal — IntersectionObserver hook for scroll fade-in
// ───────────────────────────────────────────────────────────
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    if (!('IntersectionObserver' in window)) {
      els.forEach(el => el.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -10% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ───────────────────────────────────────────────────────────
// SecHead — large EN italic + small JP sub + numeric kicker
// ───────────────────────────────────────────────────────────
function SecHead({ num, en, jp, align = 'left' }) {
  return (
    <div className="sec-head reveal" style={{ alignItems: align === 'center' ? 'center' : 'flex-start', textAlign: align }}>
      <span className="num">— {num}</span>
      <span className="en">{en}</span>
      <span className="jp">{jp}</span>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Header
// ───────────────────────────────────────────────────────────
function Header({ companyName }) {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);

  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 40);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  const close = () => setOpen(false);
  const links = [
    { en: 'About', jp: '私たちについて', href: '#about' },
    { en: 'Service', jp: '事業内容', href: '#service' },
    { en: 'Company', jp: '会社概要', href: '#company' },
    { en: 'Contact', jp: 'お問い合わせ', href: '#contact' },
  ];

  return (
    <header className={'site-header ' + (scrolled ? 'scrolled' : '')}>
      <div className="nav">
        <Logo name={companyName} />
        <nav className={'nav-links ' + (open ? 'open' : '')}>
          {links.map(l => (
            <a key={l.en} href={l.href} onClick={close}>
              <span className="en-l">{l.en}</span>
              <span className="hide-sp jp-mini" style={{ fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '.2em', marginLeft: 4 }}>
                / {l.jp}
              </span>
              <span className="hide-pc" style={{ fontSize: 13, color: 'var(--ink-soft)', marginLeft: 2 }}>
                {l.jp}
              </span>
            </a>
          ))}
        </nav>
        <button className="burger" onClick={() => setOpen(o => !o)} aria-label="メニュー">
          <svg width="26" height="20" viewBox="0 0 26 20">
            <path d={open ? 'M 4 4 L 22 16 M 22 4 L 4 16' : 'M 2 4 L 24 4 M 2 10 L 24 10 M 2 16 L 24 16'}
              stroke="#2a2520" strokeWidth="2" strokeLinecap="round" fill="none" />
          </svg>
        </button>
      </div>
    </header>
  );
}

// ───────────────────────────────────────────────────────────
// Hero
// ───────────────────────────────────────────────────────────
function Hero({ tagline, lead, heroVariant = 'mountain', heroEcho = true }) {
  // tagline can be a string OR array of lines. If string contains "\n", split.
  const lines = Array.isArray(tagline)
    ? tagline
    : String(tagline).split('\n');

  const HeroIllust = ({
    arcs: HeroArcs,
    shapes: HeroShapes,
    topo: HeroTopo,
    twocircles: HeroTwoCircles,
    thread: HeroThread,
    ripples: HeroRipples,
  }[heroVariant] || HeroThread);

  return (
    <section id="top" className="hero paper-bg">
      <div className="hero-grid">
        <div className="hero-illust reveal">
          <HeroIllust width={560} height={480} showEcho={heroEcho} />
        </div>
        <div className="hero-copy">
          <h1 className="reveal delay-1">
            {lines.map((ln, i) => {
              // Highlight strategy:
              //   2 lines → second line gets the accent
              //   3 lines → middle line gets the accent
              const isAccent =
                (lines.length === 2 && i === 1) ||
                (lines.length === 3 && i === 1);
              return (
                <span key={i} style={{ display: 'block' }} className={isAccent ? 'accent' : ''}>
                  {ln}
                </span>
              );
            })}
          </h1>
          <p className="lead reveal delay-2">{lead}</p>
          <div className="hero-actions reveal delay-3">
            <a className="btn" href="#contact">
              <span>お問い合わせ</span><span className="arr">→</span>
            </a>
            <a className="btn-ghost" href="#service">
              事業内容を見る
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────
// About
// ───────────────────────────────────────────────────────────
function About({ paragraphs }) {
  return (
    <section id="about" className="section">
      <div className="container">
        <div className="about-grid">
          <SecHead num="01" en="About us" jp="私たちについて" />
          <div className="about-body reveal delay-1">
            {paragraphs.map((p, i) => (
              <p key={i} dangerouslySetInnerHTML={{ __html: p }} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────
// Service
// ───────────────────────────────────────────────────────────
function Service({ aiIconVariant = 'robot' }) {
  const AIIcon = ({
    robot: IconAI,
    chat: IconAIChat,
    spark: IconAISpark,
  }[aiIconVariant] || IconAI);

  const items = [
    {
      n: '01',
      en: 'Website',
      jp: 'WEB制作 / 運用',
      desc: 'コーポレートサイト、サービスサイト、LPの企画・制作から、リリース後の運用代行まで。お客さまの規模に合わせた、無理のないかたちでご提案します。',
      tags: ['コーポレート', 'LP', '運用代行', '広告運用'],
      Icon: IconWeb,
      tone: '',
    },
    {
      n: '02',
      en: 'System',
      jp: 'システム開発',
      desc: '業務の小さな「面倒くさい」を仕組みで解く。社内ツール、業務システムなど、お客さまと要件整理から伴走します。',
      tags: ['業務システム', '受託開発'],
      Icon: IconSystem,
      tone: 'tone-b',
    },
    {
      n: '03',
      en: 'AI & DX',
      jp: 'AI活用 / DX支援',
      desc: '生成AIをはじめ、業務に効くテクノロジー導入を、現場の目線で。「まず何から?」のご相談から、社内の活用定着まで。',
      tags: ['生成AI導入', '社内DX', 'ChatGPT活用', '研修'],
      Icon: AIIcon,
      tone: 'tone-c',
    },
  ];

  return (
    <section id="service" className="section paper-2">
      <div className="container">
        <SecHead num="02" en="Our service" jp="事業内容" />
        <div style={{ height: 60 }} />
        <div className="service-list">
          {items.map((it, i) => {
            const reverse = i % 2 === 1;
            const Icon = it.Icon;
            return (
              <div key={i} className={'service-row reveal ' + (reverse ? 'reverse' : '')}>
                <div className={'service-visual ' + it.tone}>
                  <Icon size={Math.min(180, 200)} />
                </div>
                <div className="service-text">
                  <div className="num-big">0{i + 1}.</div>
                  <h3>{it.jp}</h3>
                  <div className="en-sub">{it.en}</div>
                  <p>{it.desc}</p>
                  <div className="service-tags">
                    {it.tags.map(t => <span key={t} className="service-tag">{t}</span>)}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────
// Works — grayed out + auto rotating
// ───────────────────────────────────────────────────────────
function Works() {
  const cases = [
    { case: 'CASE 01', co: 'A社', industry: '製造業', desc: 'コーポレートサイトリニューアル' },
    { case: 'CASE 02', co: 'B社', industry: '小売業', desc: '受発注システムの内製化支援' },
    { case: 'CASE 03', co: 'C社', industry: '士業',   desc: '生成AIによる文書作成業務の効率化' },
    { case: 'CASE 04', co: 'D社', industry: '飲食業', desc: '予約サイトの新規構築' },
    { case: 'CASE 05', co: 'E社', industry: '医療',   desc: '社内ナレッジ検索の導入支援' },
  ];
  // duplicate for seamless loop
  const loop = [...cases, ...cases];

  return (
    <section id="works" className="section">
      <div className="container works-wrap">
        <div className="works-head">
          <SecHead num="03" en="Works" jp="実績紹介" />
          <div className="private-stamp reveal">非公開 / private</div>
        </div>
        <div className="works-track-mask reveal delay-1">
          <div className="works-track">
            {loop.map((c, i) => (
              <article key={i} className="work-card">
                <div className="thumb" />
                <div className="meta">
                  <div className="case">{c.case}</div>
                  <div className="title">{c.co} ／ {c.industry}</div>
                  <div className="desc">{c.desc}</div>
                </div>
              </article>
            ))}
          </div>
        </div>
        <div className="reveal delay-2" style={{
          marginTop: 24, textAlign: 'center', color: 'var(--ink-mute)', fontSize: 13, letterSpacing: '.1em',
        }}>
          ※ 守秘義務の関係で、実績の公開は現在準備中です
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────
// Company
// ───────────────────────────────────────────────────────────
function Company({ companyName }) {
  const rows = [
    ['会社名', companyName],
    ['所在地', '東京都渋谷区道玄坂1-10-8 渋谷道玄坂東急ビル2F-C'],
    ['設立', '2022年6月'],
    // ['代表者', '●● ●●'],
    ['事業内容', 'WEB制作 / システム開発 / AI活用支援'],
    ['取引銀行', '三井住友銀行 ／ GMOあおぞらネット銀行'],
  ];
  return (
    <section id="company" className="section paper-2">
      <div className="container">
        <div className="company-grid">
          <SecHead num="03" en="Company" jp="会社概要" />
          <div className="company-table reveal delay-1">
            {rows.map(([k, v], i) => (
              <div className="company-row" key={i}>
                <div className="k">{k}</div>
                <div className="v">{v}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────
// Contact (form + thanks)
// ───────────────────────────────────────────────────────────
function CheckMark({ size = 84 }) {
  return (
    <svg viewBox="0 0 84 84" width={size} height={size} style={{ display: 'block' }} aria-hidden="true">
      <circle cx="42" cy="42" r="38" fill="#d5e8cf" />
      <circle cx="42" cy="42" r="38" fill="none" stroke="#306b3a" strokeWidth="2"
        strokeDasharray="240" strokeDashoffset="0"
        style={{ animation: 'check-stroke 1s .1s ease-out both' }}
      />
      <path d="M 26 44 L 38 56 L 60 32"
        fill="none" stroke="#306b3a" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round"
        strokeDasharray="60" strokeDashoffset="60"
        style={{ animation: 'check-stroke-in .55s .55s ease-out both' }}
      />
      <style>{`
        @keyframes check-stroke { from { stroke-dashoffset: 240; } to { stroke-dashoffset: 0; } }
        @keyframes check-stroke-in { to { stroke-dashoffset: 0; } }
      `}</style>
    </svg>
  );
}

function Contact() {
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [agreed, setAgreed] = React.useState(false);
  const formRef = React.useRef(null);

  // FORM_CONFIG is provided by form-config.js — when formAction is empty,
  // we run the dummy demo flow; otherwise we POST to Google Forms via a
  // hidden iframe so the user stays on the page.
  const cfg = (typeof window !== 'undefined' && window.FORM_CONFIG) || {
    formAction: '', entries: {},
  };
  const isLive = !!cfg.formAction;

  const submit = (e) => {
    e.preventDefault();
    setSubmitting(true);

    const finish = () => {
      setSubmitting(false);
      setSubmitted(true);
      const el = document.getElementById('contact');
      if (el) {
        const top = el.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    };

    if (isLive && formRef.current) {
      // Browser will POST the real form to a hidden iframe; we listen for
      // the iframe's load event to know when Google has received it.
      const iframe = document.getElementById('hidden-form-target');
      const onLoad = () => {
        iframe.removeEventListener('load', onLoad);
        finish();
      };
      iframe.addEventListener('load', onLoad);
      formRef.current.submit();
      // Failsafe — show thanks after 2.5s even if iframe never fires load
      // (e.g. CORS quirks). Google Forms always accepts the POST anyway.
      setTimeout(() => {
        iframe.removeEventListener('load', onLoad);
        finish();
      }, 2500);
    } else {
      // Dummy demo
      setTimeout(finish, 900);
    }
  };

  const reset = () => { setSubmitted(false); setAgreed(false); };

  return (
    <section id="contact" className="section">
      <div className="container">
        <div className="contact-grid">
          <div>
            <SecHead num="04" en="Contact" jp="お問い合わせ" />
            <p className="contact-lead reveal delay-1">
              お仕事のご依頼・ご相談、内容が定まる前のお声がけも大歓迎です。<br/>
              まずはお気軽にどうぞ。
            </p>
          </div>

          <div className="reveal delay-1">
            {!submitted ? (
              <form
                ref={formRef}
                className="form"
                onSubmit={submit}
                action={isLive ? cfg.formAction : undefined}
                method={isLive ? 'POST' : undefined}
                target={isLive ? 'hidden-form-target' : undefined}
              >
                <div className="field">
                  <label>会社名<span className="req">任意</span></label>
                  <input type="text" name={cfg.entries.company || 'company'} placeholder="株式会社○○" />
                </div>
                <div className="field">
                  <label>お名前<span className="req">必須</span></label>
                  <input type="text" name={cfg.entries.name || 'name'} placeholder="山田 太郎" required />
                </div>
                <div className="field">
                  <label>メールアドレス<span className="req">必須</span></label>
                  <input type="email" name={cfg.entries.email || 'email'} placeholder="mail@example.com" required />
                </div>
                <div className="field">
                  <label>問い合わせ内容詳細<span className="req">必須</span></label>
                  <textarea name={cfg.entries.detail || 'detail'} placeholder="ご相談したい内容をお書きください。" required></textarea>
                </div>
                {/* プライバシーポリシー準備中のため同意チェックは一旦非表示。
                    用意ができたら下記ブロックのコメントを外し、送信ボタンの
                    disabled を {submitting || !agreed} に戻すこと。
                <label className="consent">
                  <input
                    type="checkbox"
                    checked={agreed}
                    onChange={(e) => setAgreed(e.target.checked)}
                    required
                  />
                  <span className="box" aria-hidden="true">
                    <svg viewBox="0 0 16 16" width="12" height="12">
                      <path d="M 3 8 L 7 12 L 13 4" fill="none" stroke="#fff" strokeWidth="2.4"
                        strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                  <span className="text">
                    <a href="privacy.html" target="_blank" rel="noopener noreferrer">
                      プライバシーポリシー
                    </a>
                </label>
                */}
                <div className="form-actions">
                  <button type="submit" className="btn" disabled={submitting}>
                    {submitting ? <span>送信中…</span> : <><span>送信する</span><span className="arr">→</span></>}
                  </button>
                </div>
              </form>
            ) : (
              <div className="form">
                <div className="thanks">
                  <div className="check-wrap"><CheckMark size={84} /></div>
                  <div className="en">Thank you.</div>
                  <h3>お問い合わせありがとうございました</h3>
                  <p>
                    内容を確認のうえ、<br/>
                    2〜3営業日以内に担当者よりご返信いたします。
                  </p>
                  <button className="btn-ghost" onClick={reset}>もう一度送る</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────
// Footer
// ───────────────────────────────────────────────────────────
function Footer({ companyName }) {
  const top = () => window.scrollTo({ top: 0, behavior: 'smooth' });
  return (
    <footer className="site-footer">
      <div className="footer-inner">
        <Logo name={companyName} />
        <div className="copy">© 2026 {companyName} ALL RIGHTS RESERVED</div>
        <button className="scroll-top" onClick={top}>back to top ↑</button>
      </div>
    </footer>
  );
}

Object.assign(window, {
  useReveal,
  SecHead, Header, Hero, About, Service, Works, Company, Contact, Footer,
});
