/* global React */
/* ============================================================
   UDForm, site-wide unified enquiry form (right-half fields).

   ONE canonical field set + CRM field names + hidden source meta,
   imported across every subdomain so leads sync to CRM on a single
   schema. The per-page LEFT copy and SECTION background stay in each
   page's own component; UDForm owns ONLY the standardised fields,
   consent, submit, validation, and the dataLayer payload.

   AI Staff (as-form.jsx) is intentionally NOT migrated, it keeps its
   bespoke multi-step form.

   ── Canonical fields → CRM names ───────────────────────────
     姓名      contact_name_customer   (required)
     公司電郵   customer_email          (required)
     區號      phone_country_code      (required)
     電話      phone_number            (required)
     公司名稱   company_name_customer   (required)
     職銜      customer_title          (required, toggle via titleRequired)
     訊息      enquiry_message          (optional)
     同意      consent                 (required)
   ── Hidden source meta (per page) → CRM keys ───────────────
     lead_source (=channel, default "website")
     website (=full domain, e.g. ai.ud.hk)
     udba_product (=business line / subdomain, e.g. ai)
     sub_product_name (=specific product, e.g. ai staff solution)
     form_id · page_url (dataLayer only)
   Override any via source props: { subdomain, product, page,
     website, udbaProduct, subProduct, leadSource }.

   Usage:
     <window.UDForm
       theme="cdn"                       // preset name or vars object
       formId="cdn-home"
       source={{ subdomain:'cdn', page:'home', product:'cdn' }}
       submitLabel="提交查詢 →"
       titleRequired={true}
     />
   ============================================================ */

(function () {
  const PHONE_CCS = [
    ['+852', '+852 香港'], ['+86', '+86 中國內地'], ['+886', '+886 台灣'],
    ['+65', '+65 新加坡'], ['+853', '+853 澳門'], ['+1', '+1 美加'],
    ['+44', '+44 英國'], ['+81', '+81 日本'], ['+82', '+82 韓國'],
    ['+61', '+61 澳洲'], ['other', '其他'],
  ];

  // Per-subdomain theme presets. Fields use a shared dark-glass treatment;
  // presets vary the accent (button / checkbox / asterisk), select-option
  // background, tick + button ink, and font.
  const THEMES = {
    blockchain: {
      grad: 'linear-gradient(112deg,#b9c6ff 0%,#8ee8c9 62%,#bfeede 100%)',
      solid: '#8ee8c9', req: '#8ee8c9', optionBg: '#02040d',
      tickInk: '#02040d', btnInk: '#02040d',
      cardBg: 'rgba(255,255,255,0.04)', cardBorder: 'rgba(255,255,255,0.12)',
      font: "'Chakra Petch','Noto Sans HK','Noto Sans TC',sans-serif",
    },
    cdn: {
      grad: 'linear-gradient(135deg,#A855F7 0%,#7C3AED 100%)',
      solid: '#7C3AED', req: '#C4B5FD', optionBg: '#0F2A47',
      tickInk: '#fff', btnInk: '#fff',
      cardBg: 'rgba(255,255,255,0.04)', cardBorder: 'rgba(255,255,255,0.12)',
      font: "'Inter','Noto Sans HK','Noto Sans TC',sans-serif",
    },
    cloud: {
      grad: 'linear-gradient(90deg,#2D6CDF 0%,#4F7BE8 52%,#7C5CD6 100%)',
      solid: '#2D6CDF', req: '#A9C2F5', optionBg: '#0B1B33',
      tickInk: '#fff', btnInk: '#fff',
      cardBg: 'rgba(8,18,33,0.85)', cardBorder: 'rgba(255,255,255,0.14)',
      font: "'Inter','Noto Sans HK','Noto Sans TC',sans-serif",
    },
    security: {
      grad: 'linear-gradient(102deg,#86efac 0%,#67e8f9 100%)',
      solid: '#86efac', req: '#86efac', optionBg: '#020a06',
      tickInk: '#04130b', btnInk: '#04130b',
      cardBg: 'rgba(255,255,255,0.04)', cardBorder: 'rgba(255,255,255,0.12)',
      font: "'Inter','Noto Sans HK','Noto Sans TC',sans-serif",
    },
    ai: {
      grad: 'linear-gradient(90deg,#fbc106 0%,#fbc106 12.5%,#5cabe4 87.5%,#5cabe4 100%)',
      solid: '#FFC800', req: '#FFC800', optionBg: '#1B130A',
      tickInk: '#fff', btnInk: '#1A1410',
      cardBg: 'rgba(20,14,8,0.65)', cardBorder: 'rgba(237,178,85,0.22)',
      font: "'Noto Sans HK','Noto Sans TC',sans-serif",
    },
    udblue: {
      grad: 'linear-gradient(135deg,#5B6BE0 0%,#2A3795 100%)',
      solid: '#5B6BE0', req: '#AEB7F2', optionBg: '#1B2566',
      tickInk: '#fff', btnInk: '#fff',
      cardBg: 'rgba(255,255,255,0.05)', cardBorder: 'rgba(255,255,255,0.14)',
      font: "'Noto Sans HK','Noto Sans TC',sans-serif",
    },
  };

  function resolveVars(theme) {
    const t = (typeof theme === 'string' ? THEMES[theme] : theme) || THEMES.udblue;
    return {
      '--udf-grad': t.grad,
      '--udf-solid': t.solid,
      '--udf-req': t.req || t.solid,
      '--udf-option-bg': t.optionBg || '#0b1020',
      '--udf-tick-ink': t.tickInk || '#fff',
      '--udf-btn-ink': t.btnInk || '#fff',
      '--udf-card-bg': t.cardBg || 'rgba(255,255,255,0.04)',
      '--udf-card-border': t.cardBorder || 'rgba(255,255,255,0.12)',
      '--udf-font': t.font || "'Noto Sans HK','Noto Sans TC',sans-serif",
    };
  }

  const privacyHref = () =>
    (typeof window !== 'undefined' && window.__udRoot)
      ? window.__udRoot('privacy.html', 'privacy.html')
      : '/zh-Hant/privacy/';

  const UDForm = ({
    theme = 'udblue',
    formId = 'enq',
    source = {},
    submitLabel = '提交查詢 →',
    titleRequired = true,
    consentHref,
    heading,
    sub,
    card = false,
    className = '',
  }) => {
    const [consent, setConsent] = React.useState(false);
    const [consentErr, setConsentErr] = React.useState(false);
    const [sent, setSent] = React.useState(false);
    const id = (s) => `${formId}-${s}`;
    const vars = resolveVars(theme);
    const src = {
      subdomain: source.subdomain || '',
      page: source.page || '',
      product: source.product || source.page || '',
    };
    // CRM lead-routing meta (identical keys on every form across the site).
    const DOMAIN = { ai: 'ai.ud.hk', cdn: 'cdn.ud.hk', cloud: 'cloud.ud.hk', security: 'security.ud.hk', blockchain: 'blockchain.ud.hk', 'ud.hk': 'ud.hk' };
    const meta = {
      lead_source: source.leadSource || 'website',
      website: source.website || DOMAIN[src.subdomain] || (src.subdomain ? (src.subdomain.indexOf('.') >= 0 ? src.subdomain : src.subdomain + '.ud.hk') : 'ud.hk'),
      udba_product: source.udbaProduct || src.subdomain,
      sub_product_name: source.subProduct || src.product,
    };

    const onSubmit = (e) => {
      e.preventDefault();
      const form = e.currentTarget;
      const box = form.querySelector('input[name="consent"]');
      if (!box || !box.checked) { setConsentErr(true); if (box) box.focus(); return; }
      setConsentErr(false);

      // Build the canonical CRM payload from named fields and push to
      // dataLayer so GTM can forward a single, uniform lead schema.
      const fd = new FormData(form);
      const lead = {};
      fd.forEach((v, k) => { if (k !== 'consent') lead[k] = v; });
      try {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
          event: 'form_submit',
          form_id: formId,
          lead_source: meta.lead_source,
          website: meta.website,
          udba_product: meta.udba_product,
          sub_product_name: meta.sub_product_name,
          page_url: (typeof location !== 'undefined' ? location.href : ''),
          lead,
        });
      } catch (err) { /* no-op in mockup */ }
      setSent(true);
    };

    return (
      <form
        className={`udf${card ? ' udf--card' : ''}${className ? ' ' + className : ''}`}
        id={`${formId}-form`}
        data-form={src.page === 'contact' ? 'contact' : 'enquiry'}
        style={vars}
        noValidate
        onSubmit={onSubmit}
      >
        <style>{UDFORM_CSS}</style>

        {(heading || sub) && (
          <div className="udf-head">
            {heading ? <h3>{heading}</h3> : null}
            {sub ? <p className="udf-sub">{sub}</p> : null}
          </div>
        )}

        {/* Hidden source meta, CRM lead-routing keys, identical on every form */}
        <input type="hidden" name="lead_source" value={meta.lead_source} readOnly />
        <input type="hidden" name="website" value={meta.website} readOnly />
        <input type="hidden" name="udba_product" value={meta.udba_product} readOnly />
        <input type="hidden" name="sub_product_name" value={meta.sub_product_name} readOnly />
        <input type="hidden" name="form_id" value={formId} readOnly />

        {sent ? (
          <div className="udf-success">
            <h4>已收到查詢，多謝。</h4>
            <p>香港本地團隊會盡快以電郵回覆。緊急事項可經 UD 官方網站右下角即時通訊聯絡我們。</p>
          </div>
        ) : (
          <React.Fragment>
            {/* Row 1: 姓名 | 公司電郵 */}
            <div className="udf-field">
              <label htmlFor={id('name')}>姓名<span className="udf-req">*</span></label>
              <input className="udf-input" id={id('name')} name="contact_name_customer" type="text" autoComplete="name" required />
            </div>
            <div className="udf-field">
              <label htmlFor={id('email')}>公司電郵<span className="udf-req">*</span></label>
              <input className="udf-input" id={id('email')} name="customer_email" type="email" autoComplete="email" required />
            </div>

            {/* Row 2: 電話 (區號 + 號碼) */}
            <div className="udf-field full">
              <label htmlFor={id('phone')}>電話<span className="udf-req">*</span></label>
              <div className="udf-phone">
                <select className="udf-cc" id={id('phone-cc')} name="phone_country_code" aria-label="地區號碼" defaultValue="+852">
                  {PHONE_CCS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                </select>
                <input className="udf-input" id={id('phone')} name="phone_number" type="tel" inputMode="tel" autoComplete="tel" required />
              </div>
            </div>

            {/* Row 3: 公司名稱 | 職銜 */}
            <div className="udf-field">
              <label htmlFor={id('company')}>公司名稱<span className="udf-req">*</span></label>
              <input className="udf-input" id={id('company')} name="company_name_customer" type="text" autoComplete="organization" required />
            </div>
            <div className="udf-field">
              <label htmlFor={id('title')}>職銜{titleRequired ? <span className="udf-req">*</span> : <span className="udf-opt">選填</span>}</label>
              <input className="udf-input" id={id('title')} name="customer_title" type="text" autoComplete="organization-title" required={titleRequired} />
            </div>

            {/* Row 4: 訊息 */}
            <div className="udf-field full">
              <label htmlFor={id('msg')}>訊息<span className="udf-opt">選填</span></label>
              <textarea className="udf-textarea" id={id('msg')} name="enquiry_message"></textarea>
            </div>

            {/* Row 5: Consent */}
            <div className="udf-field full udf-consent">
              <label className={`udf-check${consent ? ' is-checked' : ''}`}>
                <input
                  type="checkbox"
                  name="consent"
                  id={id('consent')}
                  checked={consent}
                  onChange={(e) => { setConsent(e.target.checked); if (e.target.checked) setConsentErr(false); }}
                  required
                />
                <span className="udf-check-box" aria-hidden="true"></span>
                <span className="udf-check-text">
                  本人同意 UD 依《個人資料（私隱）條例》處理本表格提供之資料。<a href={consentHref || privacyHref()} target="_blank" rel="noopener noreferrer">查看私隱政策</a>。
                </span>
              </label>
              {consentErr && <p className="udf-consent-error">請先勾選同意條款才能提交查詢。</p>}
            </div>

            {/* Row 6: Submit */}
            <div className="udf-actions">
              <button className="udf-btn" type="submit" data-cta="submit-enquiry">{submitLabel}</button>
            </div>
          </React.Fragment>
        )}
      </form>
    );
  };

  const UDFORM_CSS = `
.udf{position:relative;display:grid;grid-template-columns:1fr 1fr;gap:22px;font-family:var(--udf-font);
  --udf-field-bg:rgba(255,255,255,0.06);--udf-field-bg-focus:rgba(255,255,255,0.12);--udf-field-border:rgba(255,255,255,0.20);--udf-text:#fff;--udf-text-soft:rgba(255,255,255,0.72)}
.udf.udf--card{padding:clamp(28px,3vw,40px);background:var(--udf-card-bg);border:1px solid var(--udf-card-border);border-radius:18px}
.udf .udf-head{grid-column:1/-1;display:flex;flex-direction:column;gap:6px;margin-bottom:2px}
.udf .udf-head h3{margin:0;font-size:21px;font-weight:700;color:var(--udf-text) !important;letter-spacing:-.2px}
.udf .udf-head .udf-sub{margin:0;font-size:14px;line-height:1.6;color:var(--udf-text-soft)}
.udf .udf-field{display:flex;flex-direction:column;gap:8px}
.udf .udf-field.full{grid-column:1/-1}
.udf .udf-field label{font-size:14px;font-weight:600;letter-spacing:.1px;color:var(--udf-text) !important;line-height:1.4;text-transform:none}
.udf .udf-opt{margin-left:8px;font-weight:400;font-size:13px;color:var(--udf-text-soft) !important}
.udf .udf-req{margin-left:4px;color:var(--udf-req);font-weight:600}
.udf .udf-input,.udf .udf-textarea,.udf .udf-cc{font:inherit;font-size:15.5px;line-height:1.5;color:var(--udf-text) !important;background:var(--udf-field-bg);border:1px solid var(--udf-field-border);border-radius:10px;padding:14px 16px;outline:none;width:100%;transition:border-color .15s,background .15s}
.udf .udf-input::placeholder,.udf .udf-textarea::placeholder{color:transparent !important}
.udf .udf-input:focus,.udf .udf-textarea:focus,.udf .udf-cc:focus{border-color:var(--udf-solid);background:var(--udf-field-bg-focus)}
.udf .udf-textarea{resize:vertical;min-height:128px;font-family:inherit}
.udf .udf-phone{display:grid;grid-template-columns:140px 1fr;gap:10px}
.udf .udf-cc{appearance:none;-webkit-appearance:none;padding:14px 36px 14px 14px;cursor:pointer;
  background-image:url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='12'%20height='8'%20viewBox='0%200%2012%208'%3E%3Cpath%20d='M1%201l5%205%205-5'%20stroke='white'%20stroke-width='1.6'%20fill='none'%20stroke-linecap='round'/%3E%3C/svg%3E");
  background-repeat:no-repeat;background-position:right 12px center}
.udf .udf-cc option{background:var(--udf-option-bg);color:var(--udf-text)}
.udf .udf-consent{margin-top:4px}
.udf .udf-check{display:grid;grid-template-columns:22px 1fr;align-items:start;gap:14px;cursor:pointer;user-select:none;position:relative}
.udf .udf-check input[type="checkbox"]{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none}
.udf .udf-check-box{width:22px;height:22px;border-radius:6px;border:1.6px solid var(--udf-field-border);background:var(--udf-field-bg);display:flex;align-items:center;justify-content:center;margin-top:1px;position:relative;transition:border-color .15s,background .15s}
.udf .udf-check-box::after{content:'';width:12px;height:7px;border-left:2px solid var(--udf-tick-ink);border-bottom:2px solid var(--udf-tick-ink);transform:rotate(-45deg) translate(1px,-2px);opacity:0;transition:opacity .12s}
.udf .udf-check.is-checked .udf-check-box{background:var(--udf-grad);border-color:transparent}
.udf .udf-check.is-checked .udf-check-box::after{opacity:1}
.udf .udf-check:hover .udf-check-box{border-color:var(--udf-solid)}
.udf .udf-check-text{font-size:13.5px;line-height:1.65;color:var(--udf-text-soft) !important;text-wrap:pretty}
.udf .udf-check-text a{color:var(--udf-text);text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:3px}
.udf .udf-consent-error{margin:8px 0 0;font-size:13.5px;font-weight:500;color:#ff9a9a}
.udf .udf-actions{grid-column:1/-1;display:flex;align-items:center;justify-content:flex-start;gap:24px;margin-top:8px;flex-wrap:wrap}
.udf .udf-btn{display:inline-flex;align-items:center;gap:10px;padding:18px 40px;font-size:16.5px;font-weight:700;letter-spacing:.3px;white-space:nowrap;color:var(--udf-btn-ink);background-color:var(--udf-solid);background-image:var(--udf-grad);border:0;border-radius:999px;cursor:pointer;font-family:inherit;box-shadow:0 8px 24px rgba(0,0,0,.35),inset 0 1px 0 rgba(255,255,255,.18);transition:transform .15s,box-shadow .15s,filter .15s}
.udf .udf-btn:hover{transform:translateY(-1px);filter:brightness(1.07);box-shadow:0 14px 32px rgba(0,0,0,.45),inset 0 1px 0 rgba(255,255,255,.22)}
.udf .udf-btn:active{transform:translateY(0);filter:brightness(.96)}
.udf .udf-success{grid-column:1/-1;display:flex;flex-direction:column;align-items:flex-start;gap:14px;padding:32px;background:var(--udf-field-bg);border:1px solid var(--udf-field-border);border-radius:14px}
.udf .udf-success h4{margin:0;font-size:20px;font-weight:700;color:var(--udf-text);letter-spacing:-.2px}
.udf .udf-success p{margin:0;font-size:13.5px;line-height:1.7;color:var(--udf-text-soft);text-wrap:pretty}
@media (max-width:640px){.udf{grid-template-columns:1fr;gap:18px}.udf .udf-actions{flex-direction:column;align-items:stretch;gap:16px}.udf .udf-btn{justify-content:center;width:100%}}
@media (max-width:480px){.udf .udf-phone{grid-template-columns:120px 1fr;gap:8px}.udf .udf-cc{font-size:14.5px;padding:14px 30px 14px 12px}}
`;

  window.UDForm = UDForm;
  window.UD_FORM_THEMES = THEMES;
})();
