<!DOCTYPE html>  
<html lang="ja">  
<head>  
  <meta charset="UTF-8">  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  <title>Text Sync Portal</title>  
  <style>  
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f4f7f6; padding: 20px; color: #333; }  
    .container { max-width: 800px; margin: 0 auto; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }  
    .hidden { display: none; }  
    input, textarea { width: 100%; margin-bottom: 15px; padding: 12px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 16px; }  
    button { padding: 12px 20px; cursor: pointer; background: #0066cc; color: #fff; border: none; border-radius: 4px; font-size: 16px; margin-right: 10px; }  
    button:hover { background: #005bb5; }  
    .memo-item { border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 4px; background: #fafafa; }  
    .memo-text { white-space: pre-wrap; word-wrap: break-word; margin-bottom: 10px; }  
    .copy-btn { background: #28a745; font-size: 14px; padding: 8px 15px; }  
    .copy-btn:hover { background: #218838; }  
    .error { color: #dc3545; font-size: 14px; margin-bottom: 15px; font-weight: bold; }  
    .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }  
  </style>  
</head>  
<body>  
  <div class="container">  
    <!-- 認証画面 -->  
    <div id="auth-section">  
      <h2>ログイン / 新規登録</h2>  
      <div id="auth-error" class="error"></div>  
      <input type="email" id="email" placeholder="メールアドレス">  
      <input type="password" id="password" placeholder="パスワード (6文字以上)">  
      <button id="login-btn">ログイン</button>  
      <button id="signup-btn">新規登録</button>  
    </div>  
  
    <!-- アプリ画面 -->  
    <div id="app-section" class="hidden">  
      <div class="header-bar">  
        <h2>テキストボックス</h2>  
        <button id="logout-btn" style="background: #6c757d;">ログアウト</button>  
      </div>  
      <textarea id="memo-input" rows="8" placeholder="ここに長文テキストを貼り付けてください..."></textarea>  
      <button id="save-btn">保存する</button>  
        
      <hr style="margin: 30px 0; border: 0; border-top: 1px solid #eee;">  
        
      <h3>保存されたテキスト</h3>  
      <div id="memo-list"></div>  
    </div>  
  </div>  
  
  <script type="module">  
    // Firebaseの読み込み  
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.13.0/firebase-app.js";  
    import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/10.13.0/firebase-auth.js";  
    import { getFirestore, collection, addDoc, query, where, orderBy, onSnapshot, serverTimestamp } from "https://www.gstatic.com/firebasejs/10.13.0/firebase-firestore.js";  
  
    // =========================================================  
  
// Import the functions you need from the SDKs you need  
import { initializeApp } from "firebase/app";  
import { getAnalytics } from "firebase/analytics";  
// TODO: Add SDKs for Firebase products that you want to use  
// https://firebase.google.com/docs/web/setup#available-libraries  
  
// Your web app's Firebase configuration  
// For Firebase JS SDK v7.20.0 and later, measurementId is optional  
const firebaseConfig = {  
  apiKey: "AIzaSyBAl8uqbqLNfMkww7Z3oPVNQxcsLMPfMn4",  
  authDomain: "my-first-project-149cc.firebaseapp.com",  
  projectId: "my-first-project-149cc",  
  storageBucket: "my-first-project-149cc.firebasestorage.app",  
  messagingSenderId: "542220346527",  
  appId: "1:542220346527:web:ebb542f2c7132de6662eaa",  
  measurementId: "G-491BWRL6WM"  
};  
  
// Initialize Firebase  
const app = initializeApp(firebaseConfig);  
const analytics = getAnalytics(app);  
  
    // =========================================================  
    const firebaseConfig = {  
      apiKey: "あなたのAPIキー",  
      authDomain: "あなたのプロジェクト.firebaseapp.com",  
      projectId: "あなたのプロジェクトID",  
      storageBucket: "あなたのプロジェクト.appspot.com",  
      messagingSenderId: "あなたの送信者ID",  
      appId: "あなたのアプリID"  
    };  
  
    // Firebase初期化  
    const app = initializeApp(firebaseConfig);  
    const auth = getAuth(app);  
    const db = getFirestore(app);  
  
    // 画面要素の取得  
    const authSection = document.getElementById('auth-section');  
    const appSection = document.getElementById('app-section');  
    const emailInput = document.getElementById('email');  
    const passwordInput = document.getElementById('password');  
    const authError = document.getElementById('auth-error');  
    const memoInput = document.getElementById('memo-input');  
    const memoList = document.getElementById('memo-list');  
  
    // ログイン状態の監視  
    onAuthStateChanged(auth, (user) => {  
      if (user) {  
        authSection.classList.add('hidden');  
        appSection.classList.remove('hidden');  
        loadMemos(user.uid);  
      } else {  
        authSection.classList.remove('hidden');  
        appSection.classList.add('hidden');  
        memoList.innerHTML = '';  
      }  
    });  
  
    // 新規登録  
    document.getElementById('signup-btn').addEventListener('click', () => {  
      authError.innerText = '';  
      createUserWithEmailAndPassword(auth, emailInput.value, passwordInput.value)  
        .catch(error => {  
          if (error.code === 'auth/operation-not-allowed') {  
            authError.innerText = "エラー: Firebaseの設定で「メール/パスワード認証」が有効になっていません。";  
          } else if (error.code === 'auth/weak-password') {  
            authError.innerText = "エラー: パスワードは6文字以上にしてください。";  
          } else if (error.code === 'auth/email-already-in-use') {  
            authError.innerText = "エラー: このメールアドレスは既に登録されています。";  
          } else {  
            authError.innerText = "エラー: " + error.message;  
          }  
        });  
    });  
  
    // ログイン  
    document.getElementById('login-btn').addEventListener('click', () => {  
      authError.innerText = '';  
      signInWithEmailAndPassword(auth, emailInput.value, passwordInput.value)  
        .catch(error => authError.innerText = "ログイン失敗: メールアドレスかパスワードが間違っています。");  
    });  
  
    // ログアウト  
    document.getElementById('logout-btn').addEventListener('click', () => signOut(auth));  
  
    // テキストの保存  
    document.getElementById('save-btn').addEventListener('click', async () => {  
      const text = memoInput.value;  
      if (!text) return;  
      const user = auth.currentUser;  
      if (user) {  
        try {  
          await addDoc(collection(db, "memos"), {  
            uid: user.uid,  
            text: text,  
            createdAt: serverTimestamp()  
          });  
          memoInput.value = ''; // 入力欄をクリア  
        } catch (error) {  
          console.error(error);  
          alert("保存に失敗しました。Firestoreのルール設定を確認してください。");  
        }  
      }  
    });  
  
    // テキスト一覧の読み込み（リアルタイム）  
    function loadMemos(uid) {  
      const q = query(collection(db, "memos"), where("uid", "==", uid), orderBy("createdAt", "desc"));  
      onSnapshot(q, (snapshot) => {  
        memoList.innerHTML = '';  
        snapshot.forEach((doc) => {  
          const data = doc.data();  
          const div = document.createElement('div');  
          div.className = 'memo-item';  
            
          const textDiv = document.createElement('div');  
          textDiv.className = 'memo-text';  
          textDiv.innerText = data.text;  
            
          const copyBtn = document.createElement('button');  
          copyBtn.className = 'copy-btn';  
          copyBtn.innerText = 'コピーする';  
          copyBtn.onclick = () => {  
            navigator.clipboard.writeText(data.text).then(() => {  
              copyBtn.innerText = 'コピー完了！';  
              setTimeout(() => copyBtn.innerText = 'コピーする', 2000);  
            });  
          };  
            
          div.appendChild(textDiv);  
          div.appendChild(copyBtn);  
          memoList.appendChild(div);  
        });  
      });  
    }  
  </script>  
</body>  
</html>  
