// Step2Target — what do you want scanned?

function Step2Target({ data, update, onNext, onBack }) {
  const { React } = window;
  const { useState } = React;

  const [errors, setErrors] = useState({});
  const [techInput, setTechInput] = useState('');

  function handleNext() {
    const errs = window.IntakeSchema.validateStep2(data);
    setErrors(errs);
    if (Object.keys(errs).length === 0) onNext();
  }

  function toggleArr(field, val) {
    const cur = data[field] || [];
    const next = cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val];
    update({ [field]: next });
  }

  function addTech(val) {
    const v = val.trim();
    if (!v) return;
    const cur = data.techStack || [];
    if (!cur.includes(v)) update({ techStack: [...cur, v] });
    setTechInput('');
  }

  function removeTech(val) {
    update({ techStack: (data.techStack || []).filter(x => x !== val) });
  }

  const TARGET_TYPES = [
    { value: 'web_app', label: 'web app' },
    { value: 'rest_api', label: 'REST API' },
    { value: 'graphql_api', label: 'GraphQL API' },
    { value: 'mobile_backend', label: 'mobile backend' },
    { value: 'ai_model_agent', label: 'AI model / agent' },
    { value: 'internal_service', label: 'internal service' },
    { value: 'source_repo', label: 'source repo' },
  ];

  const REACHABLE = [
    { value: 'yes', label: 'yes — public' },
    { value: 'no', label: 'no — internal only' },
    { value: 'partially', label: 'partially' },
    { value: 'unsure', label: 'not sure' },
  ];

  const LOC_OPTIONS = [
    { value: '', label: 'rough size (optional)' },
    { value: 'tiny', label: '< 10 endpoints' },
    { value: 'small', label: '10–50 endpoints' },
    { value: 'medium', label: '50–200 endpoints' },
    { value: 'large', label: '200–500 endpoints' },
    { value: 'xlarge', label: '500+ endpoints' },
  ];

  const ENV_OPTIONS = [
    { value: 'production', label: 'production' },
    { value: 'staging', label: 'staging' },
    { value: 'pre_production', label: 'pre-production' },
    { value: 'mixed', label: 'mixed' },
  ];

  const REPORTS = [
    { value: 'yes', label: 'yes' },
    { value: 'no', label: 'no' },
  ];

  return (
    <div className="form-step">
      <div className="form-step-heading">step 2 of 6 — target</div>

      <div className="form-group">
        <label className="form-label">what do you want scanned</label>
        <div className="check-group">
          {TARGET_TYPES.map(t => {
            const checked = (data.targetTypes || []).includes(t.value);
            return (
              <div
                key={t.value}
                className={`check-opt${checked ? ' is-checked' : ''}`}
                onClick={() => toggleArr('targetTypes', t.value)}
              >
                <div className="check-box">{checked && '✓'}</div>
                <div className="check-opt-label">{t.label}</div>
              </div>
            );
          })}
        </div>
        {errors.targetTypes && <div className="form-error">{errors.targetTypes}</div>}
      </div>

      <div className="form-group">
        <label className="form-label">publicly reachable</label>
        <div className="radio-group is-pills">
          {REACHABLE.map(r => (
            <div
              key={r.value}
              className={`radio-opt${data.publiclyReachable === r.value ? ' is-active' : ''}`}
              onClick={() => update({ publiclyReachable: r.value })}
            >
              {r.label}
            </div>
          ))}
        </div>
        {errors.publiclyReachable && <div className="form-error">{errors.publiclyReachable}</div>}
      </div>

      <div className="form-group">
        <label className="form-label">
          target URL <span className="form-label-optional">optional</span>
        </label>
        <input
          className="form-field"
          type="text"
          placeholder="https://app.example.com or /path/to/target"
          value={data.targetUrl || ''}
          onChange={e => update({ targetUrl: e.target.value })}
        />
        {errors.targetUrl && <div className="form-error">{errors.targetUrl}</div>}
      </div>

      <div className="form-group">
        <label className="form-label">
          approx. endpoints <span className="form-label-optional">optional</span>
        </label>
        <select
          className="form-field"
          value={data.approxEndpoints || ''}
          onChange={e => update({ approxEndpoints: e.target.value })}
        >
          {LOC_OPTIONS.map(o => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      </div>

      <div className="form-group">
        <label className="form-label">
          tech stack <span className="form-label-optional">optional — type and press Enter</span>
        </label>
        <div className="tag-input-wrap">
          {(data.techStack || []).map(t => (
            <span key={t} className="tag-chip">
              {t}
              <span className="tag-chip-remove" onClick={() => removeTech(t)}>×</span>
            </span>
          ))}
          <input
            className="tag-field"
            type="text"
            placeholder="e.g. Django, Next.js, Go..."
            value={techInput}
            onChange={e => setTechInput(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); addTech(techInput); }
              if (e.key === 'Backspace' && !techInput && data.techStack && data.techStack.length > 0) {
                const stack = data.techStack;
                removeTech(stack[stack.length - 1]);
              }
            }}
            onBlur={() => addTech(techInput)}
          />
        </div>
      </div>

      <div className="form-group">
        <label className="form-label">environment</label>
        <div className="radio-group is-pills">
          {ENV_OPTIONS.map(e => (
            <div
              key={e.value}
              className={`radio-opt${data.environment === e.value ? ' is-active' : ''}`}
              onClick={() => update({ environment: e.value })}
            >
              {e.label}
            </div>
          ))}
        </div>
        {errors.environment && <div className="form-error">{errors.environment}</div>}
      </div>

      <div className="form-group">
        <label className="form-label">existing pentest reports?</label>
        <div className="radio-group is-pills">
          {REPORTS.map(r => (
            <div
              key={r.value}
              className={`radio-opt${data.hasExistingReports === r.value ? ' is-active' : ''}`}
              onClick={() => update({ hasExistingReports: r.value })}
            >
              {r.label}
            </div>
          ))}
        </div>
        {errors.hasExistingReports && <div className="form-error">{errors.hasExistingReports}</div>}
      </div>

      {data.hasExistingReports === 'yes' && (
        <div className="form-group">
          <label className="form-label">
            report context <span className="form-label-optional">optional</span>
          </label>
          <textarea
            className="form-field"
            rows={3}
            placeholder="who ran them, when, what was found..."
            value={data.existingReportsDetail || ''}
            onChange={e => update({ existingReportsDetail: e.target.value })}
          />
        </div>
      )}

      <div className="form-actions">
        <button className="btn-back" onClick={onBack}>← back</button>
        <button className="btn-next" onClick={handleNext}>next →</button>
      </div>
    </div>
  );
}

window.Step2Target = Step2Target;
