// Reusable form primitives for the discovery page.
const { useState, useRef, useEffect } = React;

// --- Icons -------------------------------------------------------
const IconCheck = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="3,8.5 7,12 13,4.5" /></svg>
);
const IconArrow = ({ dir = 'right', size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: dir === 'left' ? 'rotate(180deg)' : null }}>
    <line x1="2" y1="8" x2="14" y2="8" /><polyline points="9,3 14,8 9,13" />
  </svg>
);
const IconUpload = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" /></svg>
);
const IconBig = ({ size = 32 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
);
const IconSparkle = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></svg>
);

// --- Text / textarea / select ------------------------------------
function Field({ def, value, onChange, error }) {
  const id = `f_${def.id}`;
  return (
    <div className={`field ${error ? 'has-error' : ''}`}>
      <label className="field-label" htmlFor={id}>
        <span>{def.label}{def.required ? <span className="req">*</span> : null}</span>
        {def.optional ? <span className="opt">Optional</span> : null}
      </label>
      {def.help ? <p className="field-help">{def.help}</p> : null}
      {renderControl(def, value, onChange, id)}
      {error ? <div className="error-msg">{error}</div> : null}
    </div>
  );
}

function renderControl(def, value, onChange, id) {
  switch (def.type) {
    case 'text':
    case 'email':
      return <input id={id} className="input" type={def.type === 'email' ? 'email' : 'text'}
                    value={value || ''} placeholder={def.placeholder || ''}
                    onChange={e => onChange(e.target.value)} />;
    case 'textarea':
      return <textarea id={id} className="textarea" rows={4}
                       value={value || ''} onChange={e => onChange(e.target.value)} />;
    case 'select':
      return (
        <select id={id} className="select" value={value || ''} onChange={e => onChange(e.target.value)}>
          <option value="" disabled>Select one…</option>
          {def.options.map(opt => <option key={opt} value={opt}>{opt}</option>)}
        </select>
      );
    case 'segmented':
      return (
        <div className="segmented" role="radiogroup" aria-labelledby={id}>
          {def.options.map(opt => (
            <div key={opt} role="radio" aria-checked={value === opt}
                 tabIndex={0}
                 className={`seg ${value === opt ? 'is-checked' : ''}`}
                 onClick={() => onChange(opt)}
                 onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onChange(opt); } }}>
              {opt}
            </div>
          ))}
        </div>
      );
    case 'multi':
      return <ChoiceGrid def={def} value={value || []} onChange={onChange} />;
    case 'file':
      return <UploadControl id={id} value={value} onChange={onChange} help={def.help} />;
    default:
      return null;
  }
}

function ChoiceGrid({ def, value, onChange }) {
  const max = def.max;
  const toggle = opt => {
    const has = value.includes(opt);
    if (has) onChange(value.filter(v => v !== opt));
    else {
      if (max && value.length >= max) return;
      onChange([...value, opt]);
    }
  };
  const atLimit = max && value.length >= max;
  return (
    <div>
      <div className="choice-grid">
        {def.options.map(opt => {
          const checked = value.includes(opt);
          const disabled = !checked && atLimit;
          return (
            <label key={opt} className={`choice ${checked ? 'is-checked' : ''} ${disabled ? 'is-disabled' : ''}`}>
              <input type="checkbox" checked={checked} disabled={disabled}
                     onChange={() => !disabled && toggle(opt)} />
              <span className="box"><IconCheck size={11} /></span>
              <span>{opt}</span>
            </label>
          );
        })}
      </div>
      {max ? <div className="choice-limit">Selected {value.length} of {max}.</div> : null}
    </div>
  );
}

function UploadControl({ id, value, onChange, help }) {
  const ref = useRef();
  return (
    <>
      <label htmlFor={id} className="upload">
        <span className="icon"><IconUpload /></span>
        <span className="upload-text">
          {value ? <><strong style={{color:'var(--text-primary)'}}>{value}</strong><small>Click to replace</small></>
                 : <>Click to upload or drag files here<small>{help || 'PDF, DOCX, images — up to 25 MB'}</small></>}
        </span>
        <input id={id} ref={ref} type="file" className="sr-only"
               onChange={e => {
                 const f = e.target.files && e.target.files[0];
                 if (f) onChange(f.name);
               }} />
      </label>
    </>
  );
}

// --- Progress indicator ------------------------------------------
function Progress({ steps, current, onNavigate }) {
  const totalFill = ((current + 1) / steps.length) * 100;
  return (
    <div className="form-progress">
      <div className="progress-labels">
        {steps.map((s, i) => {
          const state = i < current ? 'is-done' : i === current ? 'is-current' : '';
          return (
            <button key={s.id} type="button"
                    className={`progress-label ${state}`}
                    disabled={i > current}
                    onClick={() => i < current && onNavigate(i)}
                    style={{ background: 'none', border: 'none', textAlign: 'left', cursor: i < current ? 'pointer' : 'default', padding: 0 }}>
              <span className="n">{i < current ? <IconCheck size={10} /> : i + 1}</span>
              <span className="t">{s.shortLabel}</span>
            </button>
          );
        })}
      </div>
      <div className="progress-bar">
        <div className="progress-fill" style={{ width: `${totalFill}%` }} />
      </div>
    </div>
  );
}

// --- Deep-dive block ---------------------------------------------
function DeepDive({ dd, values, onChange, errors, display }) {
  const [open, setOpen] = useState(true);
  if (display === 'accordion') {
    return (
      <div className={`deepdive ${open ? 'is-open' : ''}`} data-variant="accordion">
        <div className="deepdive-toggle" onClick={() => setOpen(!open)}>
          <span>{dd.label} — {dd.fields.length} questions</span>
          <span className="chev"><IconArrow dir="right" size={12} /></span>
        </div>
        <div className="deepdive-content">
          {dd.fields.map(f => (
            <Field key={f.id} def={f} value={values[f.id]} error={errors[f.id]}
                   onChange={v => onChange(f.id, v)} />
          ))}
        </div>
      </div>
    );
  }
  // inline (default)
  return (
    <div className="deepdive">
      <div className="deepdive-header">
        <span className="pill">Deep-dive</span>
        <span>{dd.label}</span>
      </div>
      {dd.fields.map(f => (
        <Field key={f.id} def={f} value={values[f.id]} error={errors[f.id]}
               onChange={v => onChange(f.id, v)} />
      ))}
    </div>
  );
}

// --- Tweaks panel ------------------------------------------------
function TweaksPanel({ state, setState, open }) {
  return (
    <div className={`tweaks-panel ${open ? 'is-open' : ''}`}>
      <h4>Tweaks</h4>

      <div className="tweak">
        <span className="tweak-label">Accent color</span>
        <div className="tweak-group">
          {[['sky','Sky / Cyan'], ['amber','Amber']].map(([k, l]) => (
            <button key={k} className={`tweak-opt ${state.accent === k ? 'is-on' : ''}`}
                    onClick={() => setState({ accent: k })}>{l}</button>
          ))}
        </div>
      </div>

      <div className="tweak">
        <span className="tweak-label">Hero style</span>
        <div className="tweak-group">
          {[['minimal','Minimal'], ['stats','With stats'], ['kpi','KPI bar']].map(([k, l]) => (
            <button key={k} className={`tweak-opt ${state.heroVariant === k ? 'is-on' : ''}`}
                    onClick={() => setState({ heroVariant: k })}>{l}</button>
          ))}
        </div>
      </div>

      <div className="tweak tweak-row">
        <span className="tweak-label" style={{ margin: 0 }}>Benefit strip</span>
        <div className={`tweak-toggle ${state.showBenefitStrip ? 'is-on' : ''}`}
             onClick={() => setState({ showBenefitStrip: !state.showBenefitStrip })} />
      </div>

      <div className="tweak">
        <span className="tweak-label">Conditional deep-dives</span>
        <div className="tweak-group">
          {[['inline','Inline'], ['accordion','Accordion']].map(([k, l]) => (
            <button key={k} className={`tweak-opt ${state.conditionalDisplay === k ? 'is-on' : ''}`}
                    onClick={() => setState({ conditionalDisplay: k })}>{l}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Field, ChoiceGrid, Progress, DeepDive, TweaksPanel, IconCheck, IconArrow, IconBig, IconSparkle, IconUpload });
