/* ProHippo — Onboarding / First-time Profile Setup */

const PRACTICE_TYPES = [
  { id: "ca_individual", label: "Individual CA", emoji: "👤" },
  { id: "ca_firm",       label: "CA Firm",        emoji: "🏢" },
  { id: "cma",           label: "CMA",             emoji: "📊" },
  { id: "advocate",      label: "Tax Advocate",    emoji: "⚖️" },
  { id: "cs",            label: "Company Secy.",   emoji: "📋" },
  { id: "other",         label: "Other",           emoji: "✦" },
];

function OnboardingScreen({ user, onComplete }) {
  const [step, setStep] = React.useState(1);
  const [firmName, setFirmName] = React.useState("");
  const [practiceType, setPracticeType] = React.useState("");
  const [yourName, setYourName] = React.useState(user.displayName || "");
  const [phone, setPhone] = React.useState("");
  const [city, setCity] = React.useState("");
  const [saving, setSaving] = React.useState(false);

  const getInitials = (name) => {
    const parts = name.trim().split(/\s+/);
    if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
    return name.slice(0, 2).toUpperCase() || "??";
  };

  const handleFinish = async () => {
    if (!yourName.trim() || !phone.trim()) return;
    setSaving(true);

    const profile = {
      firmName:     firmName.trim() || yourName.trim(),
      practiceType: practiceType || "ca_individual",
      yourName:     yourName.trim(),
      phone:        phone.trim(),
      city:         city.trim(),
      email:        user.email || "",
      uid:          user.uid,
      photoURL:     user.photoURL || null,
      initials:     getInitials(firmName || yourName),
      createdAt:    new Date().toISOString(),
    };

    try {
      await firebase.firestore().collection("users").doc(user.uid).set(profile);
    } catch (_) {
      /* Firestore not set up yet — save locally so the user can still proceed */
      try { localStorage.setItem("ph_profile_" + user.uid, JSON.stringify(profile)); } catch(_2){}
    }

    onComplete(profile);
  };

  return (
    <div className="onboard-page">

      {/* Top bar */}
      <div className="onboard-topbar">
        <div className="auth-logo-row">
          <div className="auth-logo-mark" style={{background:"var(--p-primary)"}}>
            <svg viewBox="0 0 24 24" fill="none" style={{width:18,height:18}}>
              <path d="M6 4c3 0 3 4 6 4s3-4 6-4v16c-3 0-3-4-6-4s-3 4-6 4V4z" fill="white"/>
            </svg>
          </div>
          <span className="auth-logo-text" style={{color:"var(--p-primary)"}}>ProHippo</span>
        </div>
      </div>

      {/* Card */}
      <div className="onboard-card">

        {/* Progress bar */}
        <div className="onboard-progress">
          <div className={`onboard-seg ${step >= 1 ? "filled" : ""}`}/>
          <div className={`onboard-seg ${step >= 2 ? "filled" : ""}`}/>
        </div>
        <p className="onboard-step-label">Step {step} of 2</p>

        {/* ── STEP 1: Firm info ── */}
        {step === 1 && (
          <div>
            <h2 className="onboard-title">Set up your practice</h2>
            <p className="onboard-sub">Tell us about your firm — you can edit this any time in Settings</p>

            <div className="auth-field-group">
              <label className="auth-label">Firm / Practice name *</label>
              <input
                className="auth-input"
                type="text"
                placeholder="e.g. Jayesh Vyas & Co."
                value={firmName}
                onChange={e => setFirmName(e.target.value)}
                autoFocus
              />
            </div>

            <div className="auth-field-group">
              <label className="auth-label">Practice type *</label>
              <div className="onboard-type-grid">
                {PRACTICE_TYPES.map(pt => (
                  <button
                    key={pt.id}
                    type="button"
                    className={`onboard-type-btn ${practiceType === pt.id ? "selected" : ""}`}
                    onClick={() => setPracticeType(pt.id)}
                  >
                    <span className="onboard-type-emoji">{pt.emoji}</span>
                    <span>{pt.label}</span>
                  </button>
                ))}
              </div>
            </div>

            <button
              className="auth-submit-btn"
              style={{marginTop:8}}
              onClick={() => setStep(2)}
              disabled={!firmName.trim() || !practiceType}
            >
              Continue →
            </button>
          </div>
        )}

        {/* ── STEP 2: Personal info ── */}
        {step === 2 && (
          <div>
            <h2 className="onboard-title">Your profile</h2>
            <p className="onboard-sub">Quick details so clients and team members can identify you</p>

            <div className="auth-field-group">
              <label className="auth-label">Your full name *</label>
              <input
                className="auth-input"
                type="text"
                placeholder="e.g. Jayesh Vyas"
                value={yourName}
                onChange={e => setYourName(e.target.value)}
                autoFocus
              />
            </div>

            <div className="auth-field-group">
              <label className="auth-label">Phone number *</label>
              <input
                className="auth-input"
                type="tel"
                placeholder="+91 98765 43210"
                value={phone}
                onChange={e => setPhone(e.target.value)}
              />
            </div>

            <div className="auth-field-group">
              <label className="auth-label">
                City
                <span style={{fontWeight:400, color:"var(--p-text-3)", marginLeft:4}}>(optional)</span>
              </label>
              <input
                className="auth-input"
                type="text"
                placeholder="e.g. Ahmedabad"
                value={city}
                onChange={e => setCity(e.target.value)}
              />
            </div>

            <div style={{display:"flex", gap:12, marginTop:24}}>
              <button
                type="button"
                className="auth-back-btn"
                onClick={() => setStep(1)}
              >
                ← Back
              </button>
              <button
                className="auth-submit-btn"
                style={{flex:1}}
                onClick={handleFinish}
                disabled={!yourName.trim() || !phone.trim() || saving}
              >
                {saving ? "Setting up your workspace…" : "🚀 Enter ProHippo"}
              </button>
            </div>
          </div>
        )}

      </div>

      <p className="onboard-footer">
        Your data is encrypted and stored securely on Google Firebase.
      </p>
    </div>
  );
}

window.OnboardingScreen = OnboardingScreen;
